<template>
  <div class="mainContentBox">
    <avue-crud
        ref="crudRef"
        v-model:search="search"
        v-model="form"
        :data="data"
        :option="option"
        v-model:page="page"
        @row-save="createRow"
        @row-update="updateRow"
        @row-del="deleteRow"
        @search-change="searchChange"
        @search-reset="resetChange"
        @size-change="dataList"
        @current-change="dataList"
        @selection-change="selectionChange"
    >
<!--      <template #collect="scope">
        <el-switch
            active-value="1"
            inactive-value="0"
            inline-prompt
            active-text="是"
            inactive-text="否"
            v-model="scope.row.collect"
            @click="changeItem($event,scope.row)"
            class="ml-2"
            style="&#45;&#45;el-switch-on-color: #13ce66; &#45;&#45;el-switch-off-color: #ff4949"
        />
      </template>-->
      <template #menu="{size,row,index}">
        <el-button
            v-hasPerm="[buttonPermission.DEVICE.BTNS.maintenance_edit]"
            type="primary"
            link
            size="small"
            @click="showParamsPage(row)"
        ><i-ep-edit />模型
        </el-button>
      </template>
      <template #menu-left="{ size }">
        <el-button
          :disabled="toDeleteIds.length < 1"
          type="danger"
          icon="el-icon-delete"
          :size="size"
          @click="multipleDelete"
          >删除</el-button
        >
      </template>
      <template #menu-right="{}">
        <el-dropdown split-button
        >导入
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                  @click="downloadTemplate('/api/v1/device/template')"
              >
                <i-ep-download />下载模板
              </el-dropdown-item>
              <el-dropdown-item @click="importExcelData">
                <i-ep-top />导入数据
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button
            class="ml-3"
            @click="exportData('/api/v1/device/export')"
        >
          <template #icon> <i-ep-download /> </template>导出
        </el-button>
      </template>
    </avue-crud>
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="30%"
        @close="dialog.visible = false"
    >
      <el-button type="primary" @click="addItem" icon="el-icon-plus" style="margin-left:15px;width:25px;height:25px;" circle />
      <el-table
          v-loading="loading"
          ref="ruleListRef"
          :data="pageData"
          style="height: 280px"
      >
        <el-table-column
            label="参数"
            prop="fieldCode"
        >
          <template v-slot="{ row}">
            <el-input v-model="row.fieldCode"/>
          </template>
        </el-table-column>
        <el-table-column
            label="参数名称"
            prop="fieldLabel"
        >
          <template v-slot="{ row}">
            <el-input v-model="row.fieldLabel"/>
          </template>
        </el-table-column>
        <el-table-column
            label="参数值"
            prop="fieldValue"
        >
          <template v-slot="{ row}">
            <el-input v-model="row.fieldValue"/>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
        >
          <template v-slot="{ row}">
            <el-button type="danger" @click="minusItem(row)" icon="el-icon-minus" style="margin-left:15px;width:25px;height:25px;" circle />
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer" style="margin-top:20px"  align="center">
        <el-button type="primary" v-if="pageData.length>0" @click="handleSubmit">保 存</el-button>
        <el-button @click="dialog.visible = false">取消</el-button>
      </div>
    </el-dialog>
    <ExcelUpload ref="uploadRef" @finished="uploadFinished" />
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import buttonPermission from "@/common/configs/buttonPermission";
import {configSave,configList,deviceUpdateCollect} from "@/api/device";
import { useCommonStoreHook } from "@/store";
import dictDataUtil from "@/common/configs/dictDataUtil";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};
const pageData = ref([]);
const loading = ref(false); //  加载状态
const addItem = () =>{
  pageData.value.push({deviceType: clickRow.value.deviceType,deviceNo: clickRow.value.deviceNo,type: 1})
}
const minusItem = (row) =>{
  pageData.value = pageData.value.filter(item=>item.fieldCode !== row.fieldCode)
}
const changeItem =(obj,row) => {
    deviceUpdateCollect({id: row.id,collect: row.collect,deviceNo: row.deviceNo}).then((data)=>{
      if(data.code === '200'){
        ElMessage.success(data.msg);
      }else{
        ElMessage.error(data.msg);
      }
    })
}
const clickRow = ref(null)
const showParamsPage = (row)=>{
  clickRow.value = row
  configList({deviceNo: row.deviceNo}).then((data)=>{
    pageData.value = data.data
    dialog.visible = true
  })
}
const dialog = reactive({
  title: "模型设置",
  visible: false,
});
const handleSubmit = () => {
  //判断参数
  let errorData = pageData.value.filter(item=>!item.fieldCode)
  if(errorData.length > 0){
    ElMessage.warning("请填写参数");
    return
  }
  errorData = pageData.value.filter(item=>!item.fieldLabel)
  if(errorData.length > 0){
    ElMessage.warning("请填写参数名");
    return
  }
  errorData = pageData.value.filter(item=>!item.fieldValue)
  if(errorData.length > 0){
    ElMessage.warning("请填写参数值");
    return
  }
  configSave(pageData.value).then((data)=>{
    if(data.code === '200'){
      ElMessage.success(data.msg);
    }else{
      ElMessage.error(data.msg);
    }
  })
};
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/device",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } = Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const crudRef = ref(null); //crudRef.value 获取avue-crud对象

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  delBtn: false,
  selection: true,
  labelWidth: 120,
  column: [
    {
      label: "资产编号",
      prop: "deviceNo",
      search: true,
      editDisabled: true,
      width: 160,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "资产编号不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "设备名称",
      prop: "deviceName",
      search: true,
      width: 160,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "设备名称不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "型号",
      prop: "specifications",
      width: 160,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "型号不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "制造厂",
      width: 100,
      overHidden: true,
      prop: "brand",
    },
    {
      label: "购买方",
      prop: "manufacturer",
      width: 100,
      overHidden: true,
    },
    {
      label: "出厂编号",
      prop: "serialNumber",
      width: 100,
      overHidden: true,
    },
    {
      label: "出厂日期",
      prop: "serialDate",
      type: "date",
      width: 100,
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      overHidden: true,
    },
    {
      label: "启用日期",
      prop: "activationDate",
      type: "date",
      width: 100,
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      overHidden: true,
    },
    {
      label: "原值",
      prop: "originalValue",
      width: 100,
      overHidden: true,
    },
    {
      label: "所属部门",
      prop: "deptId",
      width: 100,
      overHidden: true,
      type: "tree",
      dicUrl: dictDataUtil.dept_tree_url,
      props: {
        label: "deptName",
        value: "id",
      },
      rules: [
        {
          required: true,
          message: "所属部门不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "存放位置",
      prop: "devicePosition",
      width: 100,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "存放位置不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "状态",
      prop: "state",
      type: "select",
      width: 120,
      overHidden: true,
      search: true,
      dicUrl:
        dictDataUtil.request_url +
        dictDataUtil.TYPE_CODE.device_status,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      rules: [
        {
          required: true,
          message: "状态不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "责任人",
      prop: "head",
      width: 120,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "责任人不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "备注",
      span: 24,
      overHidden: true,
      prop: "remark",
      width: 120,
      type: "textarea",
    },
    {
      label: "设备类型",
      prop: "deviceType",
      type: "select",
      width: 130,
      overHidden: true,
      search: true,
      dicUrl:
        dictDataUtil.request_url +
        dictDataUtil.TYPE_CODE.device_type,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      rules: [
        {
          required: true,
          message: "设备类型不能为空",
          trigger: "trigger",
        },
      ],
    },

    {
      label: "在线状态",
      prop: "onlineState",
      width: 100,
      display: false,
      html: true,
      formatter: (val) => {
        if (val.onlineState === "1") {
          return '<b class="el-tag el-tag--success el-tag--light">在线</b>';
        } else {
          return '<b class="el-tag el-tag--warning el-tag--light">离线</b>';
        }
      },
    },
    {
      label: "连接状态",
      prop: "collectState",
      width: 100,
      display: false,
      html: true,
      formatter: (val) => {
        if (val.onlineState === "1") {
          return '<b class="el-tag el-tag--success el-tag--light">已连接</b>';
        } else {
          return '<b class="el-tag el-tag--warning el-tag--light">未连接</b>';
        }
      },
    },
    {
      label: "计量有效期",
      prop: "meteringDate",
      type: "date",
      width: 160,
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      overHidden: true,
      rules: [
        {
          required: true,
          message: "计量有效期不能为空",
          trigger: "trigger",
        },
      ],
    },
   /* {
      label: "所属PAC",
      prop: "terminal",
      type: "select",
      width: 120,
      overHidden: true,
      search: true,
      dicUrl:import.meta.env.VITE_APP_BASE_API + "/api/v1/device/pacList",
      props: {
        label: "deviceName",
        value: "deviceNo",
      },
    },*/
    /*{
      label: "是否采集",
      prop: "collect",
      editDisplay: false,
      addDisplay: false,
      slot: true,
      width: 100,
    },*/
    /*{
      label: "所在车间",
      prop: "workshop",
      width: 160,
      overHidden: true,
    },
    {
      label: "所在工位",
      prop: "station",
      width: 160,
      overHidden: true,
    },*/
  ],
});

onMounted(() => {
  // console.log("crudRef", crudRef)
  dataList();
});
/**
 * 上传excel相关
 */
const uploadRef = ref(null);
const uploadFinished = () => {
  // 上传完成后的刷新操作
  page.currentPage = 1;
  dataList();
};
const importExcelData = () => {
  if (uploadRef.value) {
    uploadRef.value.show("/api/v1/device/import");
  }
};
</script>
