<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 #menu-left="{ size }">
        <el-button
          :disabled="toDeleteIds.length < 1"
          type="danger"
          icon="el-icon-delete"
          :size="size"
          v-hasPerm="[ButtonPermKeys.DEVICE.BTNS.allocate_del]"
          @click="multipleDelete"
          >删除</el-button
        >
      </template>
      <template #menu="{ size, row, index }">
        <el-button
          @click="maintenance(row, 0)"
          text
          v-hasPerm="[ButtonPermKeys.DEVICE.BTNS.allocate_audit]"
          type="primary"
          :size="size"
          >流程
          <template #icon>
            <svg-icon icon-class="liucheng"></svg-icon>
          </template>
        </el-button>
        <el-button
          @click="maintenance(row, 1)"
          icon="el-icon-fold"
          text
          type="primary"
          :size="size"
          >记录</el-button
        >
        <el-button
          @click="handleExport(row)"
          icon="el-icon-download"
          text
          v-hasPerm="[ButtonPermKeys.DEVICE.BTNS.allocate_export]"
          type="primary"
          :size="size"
          >导出履历</el-button
        >
      </template>
    </avue-crud>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="850px"
      @close="dialog.visible = false"
    >
      <device-page @deviceInfo="deviceInfo" />
    </el-dialog>

    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      width="750px"
      height="80%"
      @close="dialog1.visible = false"
    >
      <el-timeline style="max-width: 500px; margin-left: 100px">
        <el-timeline-item center type="success" placement="top">
          <el-card>
            <h4>调拨申请</h4>
            <p>设备编号： {{ maintenanceInfo.deviceNo }}</p>
            <p>设备名称： {{ maintenanceInfo.deviceName }}</p>
            <p>申请部门： {{ maintenanceInfo.creator }}</p>
            <p>申请人员： {{ maintenanceInfo.creator }}</p>
            <p>调拨周期： {{ maintenanceInfo.allocateCycle }}天</p>
            <p>调拨目标位置： {{ maintenanceInfo.deviceToPosition }}</p>
            <p>申请时间： {{ maintenanceInfo.created }}</p>
          </el-card>
        </el-timeline-item>

        <el-timeline-item
          center
          placement="top"
          :type="
            maintenanceInfo.state === 0
              ? 'primary'
              : maintenanceInfo.state === 0
                ? 'info'
                : 'success'
          "
        >
          <el-card v-if="viewPage">
            <h4>调拨审批</h4>
            <p>审批人员： {{ maintenanceInfo.auditUser }}</p>
            <p>
              审批结果：
              {{
                maintenanceInfo.auditUser
                  ? maintenanceInfo.auditResult === 1
                    ? "通过"
                    : "不通过"
                  : ""
              }}
            </p>
            <p>审批时间： {{ maintenanceInfo.auditTime }}</p>
          </el-card>
          <el-card v-if="!viewPage">
            <h4>调拨审批</h4>
            <el-form
              ref="maintenanceInfoForm"
              :model="maintenanceInfo"
              label-width="auto"
              style="max-width: 400px"
              :rules="rules"
            >
              <el-form-item label="审批人员" prop="auditUser">
<!--                <el-input
                  :disabled="maintenanceInfo.state !== 0"
                  v-model="maintenanceInfo.auditUser"
                />-->
                <el-select
                    v-model="maintenanceInfo.auditUser"
                    placeholder="审批人员"
                    size="large"
                    filterable
                    style="width: 240px">
                  <el-option
                      v-for="item in userList"
                      :key="item.userName"
                      :label="item.userName"
                      :value="item.userName"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="审批结果">
                <el-radio-group
                  :disabled="maintenanceInfo.state !== 0"
                  v-model="maintenanceInfo.auditResult"
                  class="ml-4"
                >
                  <el-radio :value="1">通过</el-radio>
                  <el-radio :value="2">驳回</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item style="margin-left: 45%">
                <el-button
                  type="primary"
                  v-if="maintenanceInfo.state === 0"
                  @click="maintenanceSubmit"
                  >保存</el-button
                >
              </el-form-item>
            </el-form>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import ButtonPermKeys from "@/common/configs/buttonPermission";
import { checkPerm } from "@/directive/permission";
import { getUserList } from "@/api/system/user";
import { allocateAudit, allocateExport } from "@/api/device/index";
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 permission = reactive({
  delBtn: checkPerm(ButtonPermKeys.DEVICE.BTNS.allocate_del),
  addBtn: checkPerm(ButtonPermKeys.DEVICE.BTNS.allocate_add),
  editBtn: checkPerm(ButtonPermKeys.DEVICE.BTNS.allocate_edit),
  menu: true,
});
const viewPage = ref(true);

const dialog = reactive({
  title: "设备选择",
  visible: false,
});
const dialog1 = reactive({
  title: "调拨详情",
  visible: false,
});
const userList = ref([]);
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/device/allocate",
  });
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 deviceInfo = (value) => {
  form.value.deviceNo = value.deviceNo;
  form.value.deviceName = value.deviceName;
  form.value.deviceType = value.deviceType;
  form.value.devicePosition = value.devicePosition;
  form.value.oldHead = value.head;
  form.value.devicePosition = value.devicePosition;
  form.value.oldDept = value.deptId;
  dialog.visible = false;
};
const maintenanceInfo = ref(null);
const maintenance = (row, type) => {
  viewPage.value = type === 0 ? false : true;
  maintenanceInfo.value = row;
  maintenanceInfo.value.auditResult = 1;
  dialog1.visible = true;
};
const queryUserList = () => {
  getUserList({}).then((data) => {
    userList.value = data.data;
  });
};
const handleExport = (row) => {
  allocateExport(row.deviceNo).then((response) => {
    downFile(response);
  });
};
/** 文件下载 */
const downFile = (response) => {
  const fileData = response.data;
  const fileName = decodeURI(
    response.headers["content-disposition"].split(";")[1].split("=")[1]
  );
  const fileType =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
  const blob = new Blob([fileData], { type: fileType });
  const downloadUrl = window.URL.createObjectURL(blob);
  const downloadLink = document.createElement("a");
  downloadLink.href = downloadUrl;
  downloadLink.download = fileName;
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
  window.URL.revokeObjectURL(downloadUrl);
};
const maintenanceInfoForm = ref("maintenanceInfoForm");
const maintenanceSubmit = () => {
  //alert(JSON.stringify(maintenanceInfo.value))
  maintenanceInfoForm.value.validate((isValid, invalidFields) => {
    if (isValid) {
      allocateAudit(maintenanceInfo.value).then((data) => {
        ElMessage({
          message: data.msg,
          type: "success",
        });
        dialog1.visible = false;
        dataList();
      });
    }
  });
};
const rules = reactive({
  auditUser: [{ required: true, message: "审核人员不能为空", trigger: "blur" }],
  handleContent: [
    { required: true, message: "维修内容不能为空", trigger: "blur" },
  ],
});
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  delBtn: false,
  selection: true,
  labelWidth: 150,
  viewBtn: false,
  editBtn: false,
  column: [
    {
      label: "调拨单号",
      prop: "allocateNo",
      display: false,
      width: 130,
      overHidden: true,
    },
    {
      label: "设备编号",
      prop: "deviceNo",
      width: 130,
      overHidden: true,
      search: true,
      rules: [
        {
          required: true,
          message: "设备编号不能为空",
          trigger: "trigger",
        },
      ],
      click: ({ value, column }) => {
        if (column.boxType) {
          dialog.visible = true;
        }
      },
    },
    {
      label: "设备名称",
      prop: "deviceName",
      addDisabled: true,
      width: 130,
      overHidden: true,
      search: true,
    },
    {
      label: "设备类型",
      prop: "deviceType",
      type: "select",
      width: 100,
      overHidden: true,
      addDisabled: 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: "oldDept",
      type: "tree",
      width: 130,
      overHidden: true,
      addDisabled: true,
      dicUrl: dictDataUtil.dept_tree_url,
      props: {
        label: "deptName",
        value: "id",
      },
    },
    {
      label: "新部门",
      prop: "applyDept",
      type: "tree",
      width: 130,
      overHidden: true,
      dicUrl: dictDataUtil.dept_tree_url,
      props: {
        label: "deptName",
        value: "id",
      },
      rules: [
        {
          required: true,
          message: "新部门不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "原负责人",
      prop: "oldHead",
      width: 100,
      overHidden: true,
      addDisabled: true,
    },
    {
      label: "新负责人",
      prop: "newHead",
      width: 100,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "新负责人不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "设备原位置",
      addDisabled: true,
      prop: "devicePosition",
      width: 130,
      overHidden: true,
    },
    {
      label: "设备新位置",
      prop: "deviceToPosition",
      width: 130,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "设备新位置不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "调拨周期(天)",
      prop: "allocateCycle",
      type: "number",
      width: "105",
      min: 0,
      max: 999,
      rules: [
        {
          required: true,
          message: "调拨周期不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "状态",
      prop: "state",
      display: false,
      type: "select",
      dicData: [
        { label: "待审核", value: 0 },
        { label: "通过", value: 1 },
        { label: "驳回", value: 2 },
      ],
    },
    {
      label: "申请人",
      prop: "applyUser",
      width: 130,
      overHidden: true,
      display: false,
    },
    {
      label: "申请时间",
      prop: "created",
      width: 130,
      overHidden: true,
      display: false,
    },
  ],
});

onMounted(() => {
  dataList();
  queryUserList();
});
</script>
