<template>
  <div class="tenant">
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          select: select,
        }"
        :action-list="[
          {
            text: '添加任务',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList"
      >
      </byTable>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '添加任务' : '查看任务'"
      v-model="dialogVisible"
      width="700"
      v-loading="loading"
      destroy-on-close
      :before-close="handleClose"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
        v-if="modalType == 'add'"
      >
        <template
          v-for="(cur, index) in productionProcessesList"
          :key="cur.id"
          v-slot:[cur.id]="{ item }"
        >
          <el-select
            v-model="productionObj[cur.id]"
            multiple
            placeholder="请选择负责人"
          >
            <el-option
              v-for="item in userList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </byForm>

      <byForm
        :formConfig="formConfigOne"
        :formOption="formOptionOne"
        v-model="formData.dataOne"
        ref="byformOne"
        v-else
      >
        <template #list>
          <div style="width: 100%">
            <el-table :data="formData.dataOne.productionTaskDetailList">
              <el-table-column prop="productSn" label="产品SN" />
              <el-table-column
                prop="productionProcessesName"
                label="当前工序"
              />
              <el-table-column prop="cumulativeTime" label="累计耗时" />
              <el-table-column
                label="工序状态"
                prop="processesStatus"
                :formatter="
                  (row) =>
                    dictValueLabel(row.processesStatus, processesStatusData)
                "
              />
            </el-table>
          </div>
        </template>
      </byForm>

      <template #footer>
        <el-button @click="handleClose" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm()"
          size="large"
          :loading="submitLoading"
          v-if="modalType == 'add'"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="打印"
      v-if="printDialog"
      v-model="printDialog"
      width="500"
    >
      <div
        style="height: calc(100vh - 300px); overflow: auto; padding-right: 20px"
      >
        <div id="pdfDom">
          <div
            v-for="item in qrList"
            :key="item.productSn"
            style="border: 1px solid #000; padding: 10px; margin-bottom: 20px"
          >
            <div style="display: flex">
              <div :ref="item.productSn"></div>
              <div
                style="
                  margin-left: 20px;
                  display: flex;
                  padding: 10px 0;
                  flex-direction: column;
                  justify-content: space-between;
                "
              >
                <div class="print-row">产品：{{ printData.productName }}</div>
                <div class="print-row">客户：{{ printData.customerName }}</div>
              </div>
            </div>
            <div
              style="
                font-size: 16px;
                font-weight: 700;
                color: #000;
                margin-top: 10px;
              "
            >
              {{ item.productSn }}
            </div>
            <!-- 换页 -->
            <div style="page-break-after: always"></div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="printDialog = false" size="large">取 消</el-button>
        <el-button type="primary" v-print="printObj" size="large"
          >打 印</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";
import QRCode from "qrcodejs2-fix";

const { proxy } = getCurrentInstance();
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
  },
});
const processesStatusData = ref([
  {
    label: "未开始",
    value: "0",
  },
  {
    label: "进行中",
    value: "1",
  },
  {
    label: "驳回",
    value: "2",
  },
  {
    label: "完成",
    value: "3",
  },
]);
const dialogVisible = ref(false);
const modalType = ref("add");
const rules = ref({
  productionPlanId: [
    { required: true, message: "请选择生产计划", trigger: "change" },
  ],
  dueDate: [{ required: true, message: "请选择完成期限", trigger: "change" }],
  quantity: [{ required: true, message: "请输入生产数量", trigger: "blur" }],
});
const selectConfig = reactive([]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "计划单号",
        prop: "productionPlanCode",
      },
    },

    {
      attrs: {
        label: "任务编码",
        prop: "code",
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "规格型号",
        prop: "productSpec",
      },
    },
    {
      attrs: {
        label: "任务数量",
        prop: "quantity",
      },
    },

    {
      attrs: {
        label: "完成期限",
        prop: "dueDate",
      },
    },

    {
      attrs: {
        label: "操作",
        width: "120",
        align: "center",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "查看",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "打印",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              handlePrint(row);
            },
          },
        ];
      },
    },
  ];
});
const formData = reactive({
  data: {},
  dataOne: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formOptionOne = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = computed(() => {
  return [
    {
      type: "select",
      prop: "productionPlanId",
      label: "生产计划",
      required: true,
      filterable: true,
      data: planData.value,
      fn: (val) => {
        changeFn(val);
      },
      style: {
        width: "50%",
      },
    },
    {
      type: "input",
      itemType: "text",
      prop: "productName",
      label: "产品名称",
      disabled: true,
      style: {
        width: "50%",
      },
    },
    {
      type: "input",
      itemType: "text",
      prop: "productSpec",
      label: "规格型号",
      disabled: true,
      style: {
        width: "50%",
      },
    },
    {
      type: "input",
      itemType: "text",
      prop: "waitQuantity",
      label: "待排程数量",
      disabled: true,
      style: {
        width: "50%",
      },
    },
    {
      type: "number",
      prop: "quantity",
      label: "任务数量",
      precision: 0,
      min: 1,
      controls: false,
      style: {
        width: "50%",
      },
    },
    {
      type: "date",
      itemType: "date",
      prop: "dueDate",
      label: "完成期限",
      required: true,
      style: {
        width: "50%",
      },
    },
  ];
});
const formConfigOne = computed(() => {
  return [
    {
      type: "select",
      prop: "productionPlanId",
      label: "生产计划",
      required: true,
      filterable: true,
      data: planDataOne.value,
      fn: (val) => {
        changeFn(val);
      },
      style: {
        width: "50%",
      },
    },
    {
      type: "input",
      itemType: "text",
      prop: "productName",
      label: "产品名称",
      disabled: true,
      style: {
        width: "50%",
      },
    },
    {
      type: "input",
      itemType: "text",
      prop: "productSpec",
      label: "规格型号",
      disabled: true,
      style: {
        width: "50%",
      },
    },
    {
      type: "input",
      itemType: "text",
      prop: "waitQuantity",
      label: "待排程数量",
      disabled: true,
      style: {
        width: "50%",
      },
      isShow: modalType.value == "add",
    },
    {
      type: "number",
      prop: "quantity",
      label: "任务数量",
      precision: 0,
      min: 1,
      controls: false,
      style: {
        width: "50%",
      },
    },
    {
      type: "date",
      itemType: "date",
      prop: "dueDate",
      label: "完成期限",
      required: true,
      style: {
        width: "50%",
      },
    },
    {
      type: "slot",
      slotName: "list",
      label: "产品明细",
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/productionTask/page", sourceList.value.pagination)
    .then((message) => {
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formOption.disabled = false;
  formData.data = {};
};

const submitForm = () => {
  byform.value.handleSubmit(() => {
    if (Number(formData.data.quantity) > Number(formData.data.waitQuantity)) {
      return ElMessage({
        message: "任务数量不可大于待排程数量",
        type: "info",
      });
    }
    // if (proxy.compareTime(formData.data.startDate, formData.data.dueDate)) {
    //   return ElMessage({
    //     message: "完成期限不可小于计划开始时间",
    //     type: "info",
    //   });
    // }
    for (const key in productionObj.value) {
      if (productionObj.value[key] && productionObj.value[key].length > 0) {
      } else {
        return ElMessage({
          message: "所有工序都需选择负责人！",
          type: "info",
        });
      }
    }
    formData.data.taskProcessesUser = JSON.stringify(productionObj.value);
    submitLoading.value = true;
    proxy.post("/productionTask/addByJxst", formData.data).then(
      () => {
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        handleClose();
        submitLoading.value = false;
        getList();
        getDict();
      },
      (err) => {
        console.log(err);
        submitLoading.value = false;
      }
    );
  });
};
const getDtl = (row) => {
  modalType.value = "detail";
  formOptionOne.disabled = true;
  proxy.post("/productionTask/detailByJxst", { id: row.id }).then((res) => {
    formData.dataOne = res;
    formData.dataOne.waitQuantity = res.remainingQuantity;
    dialogVisible.value = true;
  });
};
const userList = ref([]);
const planData = ref([]);
const planDataOne = ref([]);

const statusData = ref([
  {
    label: "未开始",
    value: "0",
  },
  {
    label: "进行中",
    value: "1",
  },
  {
    label: "完成",
    value: "2",
  },
]);

const getDict = () => {
  proxy
    .get("/tenantUser/list", {
      pageNum: 1,
      pageSize: 10000,
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      userList.value = res.rows.map((item) => {
        return {
          label: item.nickName,
          value: item.userId,
        };
      });
    });

  proxy
    .post("/productionPlan/page", {
      pageNum: 1,
      pageSize: 9999,
      isRemaining: "1",
    })
    .then((res) => {
      planData.value = res.rows.map((x) => ({
        label: x.code + `（${x.startDate}-${x.stopDate}）`,
        value: x.id,
        ...x,
      }));
    });

  proxy
    .post("/productionPlan/page", {
      pageNum: 1,
      pageSize: 9999,
    })
    .then((res) => {
      planDataOne.value = res.rows.map((x) => ({
        label: x.code,
        value: x.id,
        ...x,
      }));
    });
};
getDict();
getList();
const changeId = ref("");
const changeFn = (val) => {
  const current =
    modalType.value == "add"
      ? planData.value.find((x) => x.value == val)
      : planDataOne.value.find((x) => x.value == val);
  if (current) {
    formData.data.productName = current.productName;
    formData.data.productSpec = current.productSpec;
    formData.data.waitQuantity = current.remainingQuantity;
  }
  if (
    productionProcessesList.value &&
    productionProcessesList.value.length > 0
  ) {
    // changeId.value = productionProcessesList.value[0].id;
    // const index = formConfig.value.findIndex(
    //   (x) => x.slotName === changeId.value
    // );
    formConfig.value.splice(6, productionProcessesList.value.length);
    productionProcessesList.value = [];
    productionObj.value = {};
  }
  getProductionDetails(val);
};

const productionProcessesList = ref([]);
const productionObj = ref({});
const getProductionDetails = (id) => {
  proxy.post("/productionPlan/detail", { id }).then((res) => {
    productionProcessesList.value = res.productionProcessesList;
    for (let i = 0; i < productionProcessesList.value.length; i++) {
      const e = productionProcessesList.value[i];
      formConfig.value.push({
        type: "slot",
        label: e.name + " 负责人",
        slotName: e.id,
      });
      productionObj.value[e.id] = [];
    }
  });
};
const handleClose = () => {
  if (
    productionProcessesList.value &&
    productionProcessesList.value.length > 0
  ) {
    formConfig.value.splice(6, productionProcessesList.value.length);
  }
  productionProcessesList.value = [];
  productionObj.value = {};
  dialogVisible.value = false;
};

const printDialog = ref(false);
const printData = ref({});
const qrList = ref([]);
const handlePrint = (row) => {
  const { code, quantity } = row;
  const arr = [];
  for (let i = 0; i < quantity; i++) {
    let key = i + 1 + "";
    key = key.padStart(3, "0");
    let obj = {
      productSn: code + "-" + key,
    };
    arr.push(obj);
  }
  qrList.value = arr;
  printData.value = {
    customerName: row.customerName,
    productName: row.productName + `（${row.productSpec}）`,
  };
  printDialog.value = true;
  nextTick(() => {
    for (let i = 0; i < qrList.value.length; i++) {
      const ele = qrList.value[i];
      proxy.$refs[ele.productSn][0].innerHTML = ""; //清除二维码方法一
      new QRCode(proxy.$refs[ele.productSn][0], {
        text: ele.productSn, //页面地址 ,如果页面需要参数传递请注意哈希模式#
        width: 100,
        height: 100,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });
    }
  });
};
const printObj = ref({
  id: "pdfDom",
  popTitle: "",
  extraCss:
    "https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css, https://cdn.bootcdn.net/ajax/libs/hover.css/2.3.1/css/hover-min.css",
  extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
});
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
.print-row {
  font-size: 14px;
  font-weight: 700;
  color: #000;
}
</style>
