<template>
  <div class="app-container">
    <!-- 列表 -->
    <!-- 搜索 -->
    <page-search ref="searchRef" :search-config="searchConfig" @query-click="handleQueryClick"
      @reset-click="handleResetClick" />

    <!-- 列表 -->
    <page-content ref="contentRef" :content-config="contentConfig" @add-click="handleAddClick"
      @edit-click="handleEditClick" @export-click="handleExportClick" @search-click="handleSearchClick"
      @toolbar-click="handleToolbarClick" @operat-click="handleOperatClick" @filter-change="handleFilterChange">
      <!-- <template #status="scope">
        <el-tag :type="scope.row[scope.prop] == 1 ? 'success' : 'info'">
          {{ scope.row[scope.prop] == 1 ? "启用" : "禁用" }}
        </el-tag>
      </template> -->
      <template #contentType="scope">
        {{ scope.row.contentType == "yxyPrinter" ? "云想印" : "飞鹅" }}
      </template>
      <template #subType="scope">
        {{ scope.row.subType == "label" ? "标签" : "小票" }}
      </template>
      <template #caozuo="scope">
        {{ scope }}
      </template>
      <template #gender="scope">
        <DictLabel v-model="scope.row[scope.prop]" code="gender" />
      </template>
      <template #status="scope">
        <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
          @click="statusChange($event, scope.row)"></el-switch>
      </template>
      <template #operate="scope">
        <div v-if="scope.row.connectionType != 'USB'">
          <el-button @click="handleEditClick(scope.row)" icon="Edit" type="primary" link>
            编辑
          </el-button>
          <el-button @click="handdeleteevent(scope.row)" icon="Delete" type="danger" link>
            删除
          </el-button>
        </div>
      </template>
      <!-- <template #mobile="scope">
        <el-text>{{ scope.row[scope.prop] }}</el-text>
        <copy-button v-if="scope.row[scope.prop]" :text="scope.row[scope.prop]" style="margin-left: 2px" />
      </template> -->
    </page-content>

    <!-- 新增 -->
    <!-- <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #gender="scope">
        <Dict v-model="scope.formData[scope.prop]" code="gender" />
      </template>
      <template #printTypeSlot="scope">
        <div class="row" v-for="(item, index) in printTypeList" :key="index">
          <div class="title">{{ item.label }}</div>
          <div class="cont">
            <el-checkbox-group v-model="item.values" @change="printTypeChange($event, index, scope)">
              <el-checkbox :label="item.label" :value="item.value" v-for="item in item.list"
                :key="item.value"></el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </template>
      <template #classifyPrintData="scope">
        <template v-if="scope.formData.classifyPrint == 1">
          <el-checkbox-group v-model="scope.formData.categoryIdsArr">
            <template v-for="col in PrinterTypeList" :key="col">
              <el-checkbox :value="col.id * 1" :label="col.name" />
            </template>
          </el-checkbox-group>
        </template>
      </template>
    </page-modal> -->

    <!-- 编辑 -->
    <!-- <page-modal ref="editModalRef" :modal-config="editModalConfig" @submit-click="handleSubmitClick">
      <template #gender="scope">
        <Dict v-model="scope.formData[scope.prop]" code="gender" v-bind="scope.attrs" />
      </template>
      <template #printTypeSlot="scope">
        <div class="row" v-for="(item, index) in printTypeList" :key="index">
          <div class="title">{{ item.label }}</div>
          <div class="cont">
            <el-checkbox-group v-model="item.values" @change="printTypeChange($event, index, scope)">
              <el-checkbox :label="item.label" :value="item.value" v-for="item in item.list"
                :key="item.value"></el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </template>
      <template #classifyPrintData="scope">
        <template v-if="scope.formData.classifyPrint == 1">
          <el-checkbox-group v-model="scope.formData.categoryIdsArr">
            <template v-for="col in PrinterTypeList" :key="col">
              <el-checkbox :value="col.id * 1" :label="col.name" />
            </template>
          </el-checkbox-group>
        </template>
      </template>
    </page-modal> -->

    <el-dialog :title="form.id ? '编辑打印机' : '添加打印机'" width="800px" v-model="visible" @closed="dialogClosed"
      @open="dialogOpen">
      <div style="height: 60vh;overflow-y: auto;" ref="formDivRef">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入设备名称"></el-input>
          </el-form-item>
          <el-form-item label="设备类型">
            <el-radio-group v-model="form.connectionType">
              <el-radio-button label="USB" value="USB"></el-radio-button>
              <el-radio-button label="云打印" value="云打印"></el-radio-button>
              <el-radio-button label="局域网" value="局域网"></el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="小票类型">
            <el-radio-group v-model="form.printType">
              <el-radio-button label="标签" value="label"></el-radio-button>
              <el-radio-button label="小票" value="cash"></el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="打印机品牌" prop="brand">
            <el-radio-group v-model="form.brand">
              <el-radio-button label="飞鹅"></el-radio-button>
              <el-radio-button label="云想印"></el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="ip地址/MAC地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入ip地址/MAC地址"></el-input>
          </el-form-item>
          <el-form-item label="端口" prop="port">
            <el-input v-model="form.port" placeholder="请输入端口"></el-input>
          </el-form-item>
          <el-form-item label="小票尺寸" prop="receiptSize">
            <el-radio-group v-model="form.receiptSize">
              <el-radio-button label="58mm"></el-radio-button>
              <el-radio-button label="80mm"></el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="打印数量" prop="printNum">
            <el-input-number v-model="form.printNum" :step="1" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="打印内容" prop="printContentType">
            <div class="row" v-for="(item, index) in printTypeList" :key="index">
              <div class="title">{{ item.label }}</div>
              <div class="cont">
                <el-checkbox-group v-model="item.values" @change="printTypeChange($event, index)">
                  <el-checkbox :label="item.label" :value="item.value" v-for="item in item.list"
                    :key="item.value"></el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </el-form-item>
          <!-- <el-form-item label="打印模式" prop="kitchenPrintMode">
            <el-radio-group v-model="form.kitchenPrintMode">
              <el-radio-button label="整单" value="all"></el-radio-button>
              <el-radio-button label="单个" value="only"></el-radio-button>
            </el-radio-group>
            <el-text type="info" style="margin-left: 14px;">仅针对厨房制作单的打印</el-text>
          </el-form-item> -->
          <el-form-item label="分类打印">
            <div class="column">
              <div style="display: flex;align-items: center;">
                <el-radio-group v-model="form.classifyPrint">
                  <el-radio-button label="所有" value="0"></el-radio-button>
                  <el-radio-button label="部分分类" value="1" v-if="printTypeList[1].values.length > 0"></el-radio-button>
                </el-radio-group>
                <el-text type="info" style="margin-left: 14px;">仅针对厨房制作单的打印</el-text>
              </div>
              <template v-if="form.classifyPrint == 1">
                <el-checkbox-group v-model="form.categoryIds">
                  <el-checkbox v-for="item in PrinterTypeList" :value="item.id" :label="item.name"></el-checkbox>
                </el-checkbox-group>
              </template>
            </div>
          </el-form-item>
          <el-form-item label="媒体音量">
            <el-switch v-model="form.volumeSwitch" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="启用状态">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="submitHandle">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import _ from 'lodash'
import UserAPI from "@/api/account/printer";
import type { IObject, IOperatData } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";
import addModalConfig from "./config/add";
import contentConfig from "./config/content";
import editModalConfig from "./config/edit";
import searchConfig from "./config/search";
import { options } from './config/config'
import printerApi, { type addRequest } from "@/api/account/printer";

const printTypeList = ref([
  {
    label: '前台',
    values: [],
    list: [
      { label: '客看单', value: 'GUEST_ORDER' },
      { label: '预结算单', value: 'PRE_ORDER' },
      { label: '结算单', value: 'ORDER' },
      { label: '退菜单', value: 'RETURN_ORDER' },
      { label: '退款单', value: 'REFUND_ORDER' },
    ]
  },
  {
    label: '后厨',
    values: [],
    list: [
      { label: '后厨-整单', value: 'ALL_KITCHEN' },
      { label: '后厨-分单', value: 'ONLY_KITCHEN' },
      { label: '后厨-退菜单', value: 'REFUND_KITCHEN' },
    ]
  },
  {
    label: '其它',
    values: [],
    list: [
      { label: '交班单', value: 'HANDOVER' },
      { label: '排队取号', value: 'CALL' },
      { label: '储值单', value: 'RECHARGE' },
      { label: '入库单', value: 'STOCK' },
      { label: '盘点单', value: 'STOCK_CHECK' },
      { label: '商品报表', value: 'PRODUCT_REPORT' },
      { label: '经营日报', value: 'DAY_REPORT' },
      { label: '日结单', value: 'DAY_ORDER' },
    ]
  }
])

const loading = ref(false)
const visible = ref(false)
const formRef = ref(null)
const obj = {
  id: '',
  name: '', // 设备名称
  connectionType: '云打印', // 连接方式 USB、云打印、局域网
  printType: 'cash', // 打印类型 label标签 cash小票
  brand: '', // 打印机品牌 飞鹅/云想印
  address: '', // ip地址/MAC地址
  port: '', // 端口
  receiptSize: '58mm', // 小票尺寸 58mm 80mm
  printNum: 1, // 打印数量
  printContentType: '', // 打印内容
  kitchenPrintMode: 'all', // 打印模式(厨房打印菜品) all整单 /only单个
  classifyPrint: '0', // 分类打印 0-所有 1-部分分类
  categoryIds: [], // 分类Id
  status: 1, // 0 禁用 1启用
  volumeSwitch: 1, // 媒体声音开关 0关1开
}
const form = ref({ ...obj })

const rules = {
  name: [
    {
      required: true,
      message: '请输入设备名称',
      trigger: 'blur'
    }
  ],
  brand: [
    {
      required: true,
      message: '请选择打印机品牌',
      trigger: 'change'
    }
  ],
  printNum: [
    {
      required: true,
      message: '请选择打印数量',
      trigger: 'change'
    }
  ],
  // kitchenPrintMode: [
  //   {
  //     required: true,
  //     message: '请选择打印模式',
  //     trigger: 'change'
  //   }
  // ]
}

function dialogClosed() {
  formRef.value.resetFields()
  form.value = { ...obj }
}

const formDivRef = ref(null)
async function dialogOpen() {
  await nextTick()
  if (formDivRef.value) {
    // console.log('开始滚动到顶部')
    formDivRef.value.scrollTop = 0
  }
}

// 打印类型切换
function printTypeChange(e, index, scope) {
  if (index == 1 && printTypeList.value[index].values.length == 0) {
    form.value.categoryList = []
  }

  let arr = []
  printTypeList.value.forEach(item => {
    arr.push(...item.values)
  })

  form.value.printContentType = arr.join(',')
}

function submitHandle() {
  console.log('submitHandle===', form.value);
  formRef.value.validate(async valid => {
    try {
      if (valid) {
        loading.value = true
        const data = { ...form.value }
        data.categoryIds = form.value.categoryIds.join(',')
        if (form.value.id) {
          await printerApi.edit(data)
        } else {
          await printerApi.add(data)
        }
        ElMessage.success(form.value.id ? '编辑成功' : '添加成功')
        visible.value = false

        handleQueryClick();
      }
    } catch (error) {
      console.log(error);
    }
    setTimeout(() => {
      loading.value = false
    }, 300);
  })
}

// 更改状态
async function statusChange(e, data) {
  try {
    await printerApi.edit({
      id: data.id,
      status: data.status
    });
    handleQueryClick();
  } catch (error) {
    console.log(error);
  }
}

const {
  searchRef,
  contentRef,
  addModalRef,
  editModalRef,
  handleQueryClick,
  handleResetClick,
  // handleAddClick,
  // handleEditClick,
  handleSubmitClick,
  handleExportClick,
  handleSearchClick,
  handleFilterChange,
} = usePage();
onMounted(() => {
  getPrinterType();
});
let PrinterTypeList = ref([]);
// 获取商品分类
async function getPrinterType() {
  let res = await UserAPI.getPrinterType();
  PrinterTypeList.value = res.records;
}
function handdeleteevent(item) {
  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    contentConfig.deleteAction(item.id).then(() => {
      ElMessage.success("删除成功");
      handleQueryClick();
    });
  });
}
// 新增
async function handleAddClick() {
  // addModalRef.value?.setModalVisible();
  visible.value = true
}
// 编辑
async function handleEditClick(row: IObject) {
  form.value = { ...row }
  visible.value = true

  form.value.categoryIds = form.value.categoryIds.split(',')

  const printContentTypes = row.printContentType.split(',')
  printTypeList.value.forEach(val => {
    val.values = _.map(
      _.filter(val.list, item => printContentTypes.includes(item.value)),
      'value'
    );
  })

  // editModalRef.value?.handleDisabled(false);
  // editModalRef.value?.setModalVisible();
  // // 根据id获取数据进行填充
  // let data = await UserAPI.get(row.id);
  // data.printType = data.printType.split(",");

  // if (data.categoryIds) {
  //   data.categoryIdsArr = JSON.parse(data.categoryIds);
  // } else {
  //   data.categoryIdsArr = [];
  // }
  // console.log(data.categoryIdsArr);
  // console.log(data);

  // data.classifyPrint = data.classifyPrint * 1;

  // editModalRef.value?.setFormData(data);
}
// 其他工具栏
function handleToolbarClick(name: string) {
  console.log(name);
  if (name === "custom1") {
    ElMessage.success("点击了自定义1按钮");
  }
}
// 其他操作列
async function handleOperatClick(data: IOperatData) {
  console.log(data);
  if (data.name === "detail") {
    // 禁用表单编辑
    editModalRef.value?.handleDisabled(true);
    // 打开抽屉
    editModalRef.value?.setModalVisible();
    // 根据id获取数据进行填充
    const formData = await UserAPI.getFormData(data.row.id);
    // 设置表单数据
    editModalRef.value?.setFormData(formData);
  }
}

// 切换示例
const isA = ref(true);
</script>
