<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"
      :permission="permission"
      @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.instance_edit]"
          type="primary"
          link
          size="small"
          @click="showParamsPage(row)"
          >模型
          <template #icon>
            <svg-icon icon-class="moxing" />
          </template>
        </el-button>
      </template>
      <template #menu-left="{ size }">
        <el-button
          :disabled="toDeleteIds.length < 1"
          type="danger"
          icon="el-icon-delete"
          :size="size"
          v-hasPerm="[buttonPermission.DEVICE.BTNS.instance_del]"
          @click="multipleDelete"
          >删除</el-button
        >

        <!--        <el-button
            :disabled="toDeleteIds.length < 1"
            type="refresh"
            icon="el-icon-refresh"
            :size="size"
            @click="apsSync"
        >APS同步</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 #default="{ row }">
            <el-input v-model="row.fieldCode" />
          </template>
        </el-table-column>
        <el-table-column label="参数名称" prop="fieldLabel">
          <template #default="{ row }">
            <el-input v-model="row.fieldLabel" />
          </template>
        </el-table-column>
        <el-table-column label="参数值" prop="fieldValue">
          <template #default="{ row }">
            <el-input v-model="row.fieldValue" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ 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" @click="handleSubmit">保 存</el-button>
        <el-button @click="dialog.visible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-model="dialog2.visible"
      :title="dialog2.title"
      width="70%"
      @close="dialog2.visible = false"
    >
      <choice-workshop-page @work-shop-info="workShopInfo" />
    </el-dialog>
    <el-dialog
      v-model="dialog3.visible"
      :title="dialog3.title"
      width="70%"
      @close="dialog3.visible = false"
    >
      <choice-station-page @station-info="stationInfo" />
    </el-dialog>
    <ExcelUpload ref="uploadRef" @finished="uploadFinished" />
  </div>
  <CommonTable
    ref="ctableRef"
    tableTitle="负责人选择"
    tableType="USERS"
    @selected-sure="onSelectedFinish"
  />
</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 { syncAps } from "@/api/aps";
import { useCommonStoreHook } from "@/store";
import ChoiceWorkshopPage from "../../plan/workOrder/components/choice-workshop-page.vue";
import ChoiceStationPage from "./components/choice-station-page.vue";
import dictDataUtil from "@/common/configs/dictDataUtil";
import { checkPerm } from "@/directive/permission";
import { ElMessage, ElMessageBox } from "element-plus";
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 permission = reactive({
  delBtn: checkPerm(buttonPermission.DEVICE.BTNS.instance_del),
  addBtn: checkPerm(buttonPermission.DEVICE.BTNS.instance_add),
  editBtn: checkPerm(buttonPermission.DEVICE.BTNS.instance_edit),
  menu: true,
});
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 apsSync = () => {
  ElMessageBox.confirm("是否同步所选中数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let param = { type: 1, codes: toDeleteIds.value };
    syncAps(param).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对象
const workShopInfo = (value) => {
  form.value.workshop = value.name;
  dialog2.visible = false;
};
const ctableRef = ref(null);
const onSelectedFinish = (selectedValue) => {
  form.value.head = selectedValue.userName;
};
const stationInfo = (value) => {
  form.value.station = value.name;
  dialog3.visible = false;
};
const dialog2 = reactive({
  title: "车间选择",
  visible: false,
});
const dialog3 = reactive({
  title: "工位选择",
  visible: false,
});
// 设置表格列或者其他自定义的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: "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: "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: "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: "head",
      width: 120,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "负责人不能为空",
          trigger: "trigger",
        },
      ],
      click: ({ value, column }) => {
        ctableRef.value.startSelect();
      },
    },
    {
      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: "manufacturer",
      width: 160,
      overHidden: true,
    },
    {
      label: "所属部门",
      prop: "deptId",
      width: 160,
      overHidden: true,
      type: "tree",
      dicUrl: dictDataUtil.dept_tree_url,
      props: {
        label: "deptName",
        value: "id",
      },
    },
    /*{
      label: "所在车间",
      prop: "workshop",
      width: 160,
      overHidden: true,
      click: ({ value, column }) => {
        if (column.boxType) {
          dialog2.visible = true;
        }
      },
    },
    {
      label: "所在工位",
      prop: "station",
      width: 160,
      overHidden: true,
      click: ({ value, column }) => {
        if (column.boxType) {
          /!*if(!form.value.workshop){
            ElMessage({
              message: "请先选择车间",
              type: "warning",
            });
            return;
          }*!/
          dialog3.visible = true;
        }
      },
    },*/
    {
      label: "设备位置",
      prop: "devicePosition",
      width: 160,
      overHidden: true,
    },
    {
      label: "规格",
      prop: "specifications",
      width: 160,
      overHidden: true,
    },
    {
      label: "品牌",
      width: 160,
      overHidden: true,
      prop: "brand",
    },
  ],
});

onMounted(() => {
  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>
