<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
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #list>
          <div style="width: 100%">
            <el-table :data="formData.data.productionTaskList">
              <el-table-column prop="quantity" label="任务数量" />
              <el-table-column prop="personLiableName" label="负责人" />
              <el-table-column
                prop="status"
                label="完成状态"
                :formatter="(row) => dictValueLabel(row.status, statusData)"
              />
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm()"
          size="large"
          :loading="submitLoading"
          v-if="modalType == 'add'"
        >
          确 定
        </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";

const { proxy } = getCurrentInstance();
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
  },
});
const dialogVisible = ref(false);
const modalType = ref("add");
const rules = ref({
  workOrderId: [{ required: true, message: "请选择工单", trigger: "change" }],
  startDate: [
    { required: true, message: "请选择计划开始时间", trigger: "change" },
  ],
  stopDate: [
    { required: true, message: "请选择计划结束时间", trigger: "change" },
  ],
  quantity: [{ required: true, message: "请输入计划数量", trigger: "blur" }],
});
const workOrderData = ref([]);
const workOrderDataOne = ref([]);

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

const selectConfig = reactive([
  {
    label: "计划状态",
    prop: "status",
    data: statusData.value,
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "工单单号",
        prop: "workOrderCode",
      },
    },
    {
      attrs: {
        label: "计划单号",
        prop: "code",
      },
    },
    {
      attrs: {
        label: "计划开始时间",
        prop: "startDate",
      },
    },
    {
      attrs: {
        label: "计划结束时间",
        prop: "stopDate",
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "规格型号",
        prop: "productSpec",
      },
    },
    {
      attrs: {
        label: "计划数量",
        prop: "quantity",
      },
    },

    {
      attrs: {
        label: "计划状态",
        prop: "status",
      },
      render(status) {
        return proxy.dictValueLabel(status, statusData.value);
      },
    },

    {
      attrs: {
        label: "操作",
        width: "80",
        align: "center",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "查看",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
        ];
      },
    },
  ];
});
const formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = computed(() => {
  return [
    {
      type: "select",
      prop: "workOrderId",
      label: "工单",
      required: true,
      filterable: true,
      data:
        modalType.value == "add" ? workOrderData.value : workOrderDataOne.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: "date",
      itemType: "date",
      prop: "startDate",
      label: "计划开始时间",
      required: true,
      style: {
        width: "50%",
      },
    },

    {
      type: "date",
      itemType: "date",
      prop: "stopDate",
      label: "计划结束时间",
      required: true,
      style: {
        width: "50%",
      },
    },
    {
      type: "number",
      prop: "quantity",
      label: "计划数量",
      precision: 0,
      min: 1,
      controls: false,
      style: {
        width: "50%",
      },
    },
    {
      type: "slot",
      slotName: "list",
      label: "生产任务",
      isShow: modalType.value != "add",
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/productionPlan/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.stopDate)) {
      return ElMessage({
        message: "时间选择存在问题",
        type: "info",
      });
    }
    submitLoading.value = true;
    proxy.post("/productionPlan/add", formData.data).then(
      () => {
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
        getDict();
      },
      (err) => {
        console.log(err);
        submitLoading.value = false;
      }
    );
  });
};
const getDtl = (row) => {
  modalType.value = "detail";
  formOption.disabled = true;
  proxy.post("/productionPlan/detail", { id: row.id }).then((res) => {
    formData.data = res;
    changeFn(formData.data.workOrderId);
    dialogVisible.value = true;
  });
};

const getDict = () => {
  proxy
    .post("/workOrder/page", { pageNum: 1, pageSize: 9999, isRemaining: "1" })
    .then((res) => {
      workOrderData.value = res.rows.map((x) => ({
        label: x.code,
        value: x.id,
        ...x,
      }));
    });
  proxy.post("/workOrder/page", { pageNum: 1, pageSize: 9999 }).then((res) => {
    workOrderDataOne.value = res.rows.map((x) => ({
      label: x.code,
      value: x.id,
      ...x,
    }));
  });
};
getDict();
getList();

const changeFn = (val) => {
  const current =
    modalType.value == "add"
      ? workOrderData.value.find((x) => x.value == val)
      : workOrderDataOne.value.find((x) => x.value == val);
  if (current) {
    formData.data.productName = current.productName;
    formData.data.productSpec = current.productSpec;
    formData.data.waitQuantity = current.remainingQuantity;
  }
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
