<template>
  <div class="padding" style="height: 700px; overflow: auto">
    <div class="padding">
      <div style="font-weight: bold; font-size: 16px">工单信息</div>
      <div v-if="baseData1">
        <div class="back_color padding marginTop">
          <a-descriptions title="" :column="4">
            <a-descriptions-item label="工单编号">{{ baseData1.id }}</a-descriptions-item>
            <a-descriptions-item label="优先级">
              <span v-if="baseData1.priority">
                <span v-for="(re, i) in baseData1.priority.split(',')" :key="i">
                  <span v-for="item in priorityOptions" :key="item.key">
                    <span v-if="item.value == re">{{ i > 0 ? ',' : '' }}{{ item.label }}</span>
                  </span>
                </span>
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="计划开工日期">{{
              baseData1.planStartDate
            }}</a-descriptions-item>
            <a-descriptions-item label="计划完工日期">{{
              baseData1.planEndDate
            }}</a-descriptions-item>

            <a-descriptions-item label="物料编码">{{ baseData1.materialNo }}</a-descriptions-item>
            <a-descriptions-item label="物料名称">{{ baseData1.materialName }}</a-descriptions-item>

            <a-descriptions-item label="计划产量">{{ baseData1.planNum }}</a-descriptions-item>
            <a-descriptions-item label="单位">{{ baseData1.unity }} </a-descriptions-item>

            <a-descriptions-item label="车间">
              <span v-if="baseData1.carId">
                <span v-for="(re, i) in baseData1.carId.split(',')" :key="i">
                  <span v-for="item in carIdOptions" :key="item.key">
                    <span v-if="item.value == re">{{ i > 0 ? ',' : '' }}{{ item.label }}</span>
                  </span>
                </span>
              </span></a-descriptions-item
            >
            <a-descriptions-item label="产线">
              <span v-if="baseData1.lineId">
                <span v-for="(re, i) in baseData1.lineId.split(',')" :key="i">
                  <span v-for="item in lineIdOptions" :key="item.key">
                    <span v-if="item.value == re">{{ i > 0 ? ',' : '' }}{{ item.label }}</span>
                  </span>
                </span>
              </span></a-descriptions-item
            >
            <!-- <a-descriptions-item label="工艺">
              <span v-if="baseData1.craftId">
                <span v-for="(re, i) in baseData1.craftId.split(',')" :key="i">
                  <span v-for="item in stepOptions" :key="item.key">
                    <span v-if="item.value == re">{{ i > 0 ? ',' : '' }}{{ item.label }}</span>
                  </span>
                </span>
              </span></a-descriptions-item
            > -->
            <a-descriptions-item label="生产订单号">{{ baseData1.orderNo }}</a-descriptions-item>
            <a-descriptions-item label="生产计划编号">{{ baseData1.planId }}</a-descriptions-item>
            <a-descriptions-item label="上线日期">{{ baseData1.onlineDate }}</a-descriptions-item>
            <a-descriptions-item label="销售单号">{{ baseData1.saleOrderNo }}</a-descriptions-item>

            <a-descriptions-item label="创建人">{{ baseData1.createUserName }}</a-descriptions-item>

            <a-descriptions-item label="创建时间">{{ baseData1.createDate }}</a-descriptions-item>
            <a-descriptions-item label="备注">{{ baseData1.remark }}</a-descriptions-item>
          </a-descriptions>
        </div>
      </div>
    </div>

    <div class="padding">
      <div style="display: flex; justify-content: space-between">
        <div style="font-weight: bold; font-size: 16px"
          >工艺路线：
          <span v-if="baseData1 && baseData1.craftId">
            <span v-for="(re, i) in baseData1.craftId.split(',')" :key="i">
              <span v-for="item in stepOptions" :key="item.key">
                <span v-if="item.value == re">{{ i > 0 ? ',' : '' }}{{ item.label }}</span>
              </span>
            </span>
          </span></div
        >
        <div
          >设为常用：
          <a-switch
            v-model:checked="baseData1.isDefaultStep"
            :unCheckedValue="0"
            :checkedValue="1"
            :disabled="!rowData.isUpdate || !baseData1.craftId"
            @change="updateWork"
          />
          <a-button
            v-if="rowData.isUpdate"
            @click="multipleDialog = true"
            type="primary"
            style="margin-left: 12px"
            >选择工艺路线</a-button
          >
          <a-button
            v-if="rowData.isUpdate"
            @click="handleMergeUser"
            type="primary"
            style="margin-left: 12px"
            >合批派工</a-button
          >
        </div>
      </div>
      <a-table
        :columns="filterColum(columnsProp.columns)"
        :bordered="true"
        :pagination="true"
        :data-source="detailList"
        :scroll="{ x: 'max-content' }"
        :row-selection="{ selectedRowKeys: selectedKeysStep, onChange: onSelectChangeStep }"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key !== 'action'">
            <template v-if="column.dataIndex === 'index'">
              {{ index + 1 }}
            </template>
          </template>
          <template v-if="column.key == 'action'">
            <a @click="handleStepuser(record)"> 派工 </a>
            <a @click="handleStepuserView(record)"> 详情 </a>
          </template>
          <template v-if="column.dataIndex === 'taskNum'">
            <a-input-number
              :min="0"
              :step="1"
              :disabled="!rowData.isUpdate || !(!record.state || record.state == '0')"
              v-model:value="record.taskNum"
              placeholder="请输入"
              @change="updateStep(record)"
            />
          </template>
          <template v-if="column.dataIndex === 'state'">
            {{ !record.state || record.state == '0' ? '未派工' : '' }}
            {{ record.state == '1' ? '部分派工' : '' }}
            {{ record.state == '2' ? '派工完成' : '' }}
          </template>
        </template>
      </a-table>
    </div>
    <a-divider />
    <div class="modelfooter" v-if="rowData.isUpdate">
      <!-- <a-button @click="handleClose">取消</a-button> -->
      <a-button @click="handleSubmit" type="primary" style="margin-left: 12px">确认</a-button>
    </div>

    <a-modal
      :maskClosable="false"
      title="工艺路线选择"
      v-model:visible="multipleDialog"
      :width="1000"
      :footer="null"
    >
      <div style="padding-bottom: 50px">
        <a-table
          :dataSource="craftDataList"
          :columns="[
            {
              dataIndex: 'process_code',
              title: '工艺编码',
              width: 150,
            },
            {
              dataIndex: 'process_name',
              title: '工艺路线名称',
              width: 150,
            },
            {
              dataIndex: 'remark',
              title: '描述',
              width: 150,
            },
          ]"
          :row-selection="{
            selectedRowKeys: selectedKeys,
            onChange: onSelectChange,
            type: 'radio',
          }"
          :scroll="{ y: '300px' }"
        />
      </div>
      <div class="modelfooter" v-if="rowData.isUpdate">
        <a-button @click="multipleDialog = false">取消</a-button>
        <a-button @click="handleSelectGroup" type="primary" style="margin-left: 12px"
          >确认</a-button
        >
      </div>
    </a-modal>

    <a-modal
      :maskClosable="false"
      title="派工操作"
      v-model:visible="visibleModa"
      :confirm-loading="confirmLoading"
      width="90%"
      :body-style="{
        height: '700px',
        overflow: 'hidden',
        overflowY: 'scroll',
      }"
      :style="{
        left: '5%',
        top: '120px',
      }"
      :footer="null"
    >
      <stepuserPropsModal
        v-if="visibleModa"
        :rowData="rowDatauser"
        @cancel="visibleModa = false"
        @success="handleSuccessUser"
      ></stepuserPropsModal>
    </a-modal>
    <a-modal
      :maskClosable="false"
      title="派工操作"
      v-model:visible="visibleModabatch"
      :confirm-loading="confirmLoading"
      width="90%"
      :body-style="{
        height: '700px',
        overflow: 'hidden',
        overflowY: 'scroll',
      }"
      :style="{
        left: '5%',
        top: '120px',
      }"
      :footer="null"
    >
      <stepuserBatchPropsModal
        v-if="visibleModabatch"
        :rowData="rowDatauserbatch"
        @cancel="visibleModabatch = false"
        @success="handleSuccessUser"
      ></stepuserBatchPropsModal>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { uploadApi } from '/@/api/sys/upload';
  import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
  import { ref, reactive, watch, onMounted, createVNode } from 'vue';
  // import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import {
    getDicItem,
    getMesFactoryListByType,
    getMesGoupList,
    getProcessTechList,
    getProcessTechStepList,
    getWorkOrderStepList,
  } from '/@/api/mes/common';

  import { getMesProOrderwork, updateMesProOrderwork } from '/@/api/mes/proorderwork';
  import {
    updateMesProOrderworkStepBatch,
    updateMesProOrderworkStep,
  } from '/@/api/mes/proorderworkstep';
  // import SelectUser from '/@/components/Form/src/components/SelectUser.vue';
  import stepuserPropsModal from './stepuserPropsModal.vue';
  import stepuserBatchPropsModal from './stepuserBatchPropsModal.vue';

  // import AutoCodeRule from '/@/components/Form/src/components/AutoCodeRule.vue';
  // import { XjrDatePicker } from '/@/components/DatePicker';
  // import { MultipleSelect } from '/@/components/MultiplePopup';
  // import Upload from '/@/components/Form/src/components/Upload.vue';
  // import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);

  const selectedKeysStep = ref<string[]>([]);
  const selectedRowsDataStep = ref<any[]>([]);
  const { notification } = useMessage();
  const { t } = useI18n();
  let props = defineProps(['rowData']);
  const rowData: {
    id: string;
    isUpdate: boolean;
    flag: string;
  } = reactive({
    id: '',
    isUpdate: false,
    flag: '',
  });

  const detailList = ref<any[]>([]);
  const craftList = ref<any[]>([]);
  // const format = ref('YYYY-MM-DD HH:mm:ss');
  const multipleDialog = ref<boolean>(false);
  function filterColum(column) {
    return column.filter((o) => {
      return o.show == false ? false : true;
    });
  }
  function handleSelectGroup() {
    //选择工艺
    console.log('selectedRowsData', selectedRowsData.value);
    baseData1.value.craftId = '';
    selectedRowsData.value.forEach((ele) => {
      baseData1.value.craftId = ele.id;
    });
    if (baseData1.value.craftId && baseData1.value.craftId.length > 0) updateWork();
    //查询明细：
    getStepDetailList();

    multipleDialog.value = false;
  }
  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }
  function onSelectChangeStep(selectedRowKeys: [], selectedRows) {
    selectedKeysStep.value = selectedRowKeys;
    selectedRowsDataStep.value = selectedRows;
  }
  // const removeList = (index) => {
  //   detailList.value.splice(index, 1);
  // };
  const baseData1 = ref<any>({});
  const formData = ref<any>({
    groupId: '',
    groupNo: '',
    groupName: '',
    remark: '',
    sendType: '1', //派单类型1-工单指派，2-工序派单
  });

  const emit = defineEmits(['cancel', 'success']);
  // const formRef = ref();
  onMounted(async () => {
    rowData.id = props.rowData.id;
    rowData.isUpdate = props.rowData.isUpdate;
    rowData.flag = props.rowData.flag;
    console.log('row===', rowData);

    getDetailData();

    priorityOptions.value = await getDicItem('1689840965516009473');
    unityOptions.value = await getDicItem('1688808244736008194');

    carIdOptions.value = await getMesFactoryListByType(1, '');
    lineIdOptions.value = await getMesFactoryListByType(2, '');
    stepOptions.value = await getProcessTechList('');
    groupOptions.value = await getMesGoupList();
  });

  watch(
    () => props.rowData,
    (val) => {
      console.log('监听', val);
      if (val) {
        rowData.id = props.rowData.id;
        rowData.isUpdate = props.rowData.isUpdate;
        rowData.flag = props.rowData.flag;
        formData.value = {};
        getDetailData();
      }
    },
  );
  async function handleSuccessUser() {
    visibleModa.value = false;
    visibleModabatch.value = false;
    selectedKeysStep.value = '';
    selectedRowsDataStep.value = [];
    await getStepList();
  }
  const confirmLoading = ref<boolean>(false);
  const visibleModa = ref<boolean>(false);
  const rowDatauser = ref({});
  function handleStepuser(record: Recordable) {
    rowDatauser.value.id = record.id;
    console.log('record===', record);
    rowDatauser.value = record;
    rowDatauser.value.isUpdate = true;
    rowDatauser.value.flag = new Date();
    visibleModa.value = true;
  }
  function handleStepuserView(record: Recordable) {
    rowDatauser.value.id = record.id;
    console.log('record===', record);
    rowDatauser.value = record;
    rowDatauser.value.isUpdate = false;
    rowDatauser.value.flag = new Date();
    visibleModa.value = true;
  }
  const priorityOptions = ref<any[]>([]);
  const unityOptions = ref<any[]>([]);
  const carIdOptions = ref<any[]>([]);
  const lineIdOptions = ref<any[]>([]);
  const stepOptions = ref<any[]>([]);
  const groupOptions = ref<any[]>([]);
  // const workIdList = ref<any[]>([]);
  // const baseDataList = ref<any[]>([]);
  const craftDataList = ref<any[]>([]);

  const getDetailData = async () => {
    // baseDataList.value = [];
    const data = await getMesProOrderwork(rowData.id);
    // baseDataList.value.push(data);
    baseData1.value = data;
    baseData1.value.sendType = '2';
    //查询工艺路线：
    craftDataList.value = await getProcessTechList(baseData1.value?.materialId);
    // console.log('craftTemp', craftTemp);
    // craftTemp?.then((result) => {
    //   craftDataList.value = result;
    // });
    if (craftDataList.value && craftDataList.value.length == 1)
      baseData1.value.craftId = craftDataList.value[0].id;

    await getStepList();
    if (detailList.value && detailList.value.length > 0) {
      console.log('编辑', detailList.value);
    } else {
      if (baseData1.value.craftId) {
        getStepDetailList();
      } else {
        // 手动选择工艺
      }
    }
  };
  async function getStepDetailList() {
    if (baseData1.value.craftId) {
      detailList.value = [];
      let result = await getProcessTechStepList(baseData1.value.craftId);
      // list?.then((result) => {
      //Promise中如何取到[[PromiseResult]]
      console.log('result', result);
      if (result && result instanceof Array)
        result.forEach((ele) => {
          detailList.value.push({
            workId: baseData1.value.id,
            workNo: baseData1.value.workNo,
            workName: baseData1.value.workName,
            stepId: ele.id,
            stepNo: ele.process_no,
            stepName: ele.process_name,
            taskNum: ele.step_num,
            stepPrice: ele.step_price,
            state: '0',
            sendNum: '',
          });
        });
      // });
      detailList.value.mesProOrderworkStepList = detailList.value;

      await updateMesProOrderworkStepBatch({
        workId: baseData1.value.id,
        detailList: detailList.value,
      });
      await getStepList();
    }
  }
  async function getStepList() {
    let stepList = await getWorkOrderStepList(baseData1.value?.id);
    detailList.value = stepList?.list;
    for (let i = 0; i < detailList.value.length; i++) {
      detailList.value[i].key = i;
    }
  }
  const visibleModabatch = ref<boolean>(false);
  const rowDatauserbatch = ref({});
  function handleMergeUser() {
    if (!selectedRowsDataStep.value || selectedRowsDataStep.value.length == 0) {
      notification.error({
        message: 'Tip',
        description: t('请选择需要合批指派的记录'),
      }); //提示消息
      return;
    }
    rowDatauserbatch.value.list = selectedRowsDataStep.value;
    rowDatauserbatch.value.sendUser = '';
    rowDatauserbatch.value.isUpdate = true;
    rowDatauserbatch.value.flag = new Date();
    console.log('rowDatauserbatch.value', rowDatauserbatch.value);
    visibleModabatch.value = true;
  }
  function updateStep(record: Recordable) {
    //更新步骤
    updateMesProOrderworkStep(record);
  }
  function handleEditStepUser() {}
  function handleViewStepUser() {}
  async function updateWork() {
    try {
      await updateMesProOrderwork(baseData1.value);
      // notification.success({
      //   message: 'Tip',
      //   description: t('编辑'),
      // }); //提示消息
      // // formRef.value.resetFields();
      // emit('success');
    } finally {
    }
  }
  function handleSubmit() {
    Modal.confirm({
      title: '提示信息',
      content: '是否确认派工完成并提交到下一步？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        baseData1.value.state = 1; //待生产
        updateMesProOrderwork(baseData1.value).then((_) => {
          notification.success({
            message: 'Tip',
            description: t('工序指派成功！'),
          });
          emit('success');
        });
      },
      onCancel() {},
    });
  }
  function handleClose() {
    emit('cancel');
  }

  const columnsProp = {
    columns: [
      {
        title: '工单编号',
        dataIndex: 'workNo',
      },
      {
        title: '工序编码',
        dataIndex: 'stepNo',
      },
      {
        title: '工序名称',
        dataIndex: 'stepName',
      },
      {
        title: '任务总量',
        dataIndex: 'taskNum',
      },
      {
        title: '工序单价',
        dataIndex: 'stepPrice',
      },
      {
        title: '状态',
        dataIndex: 'state',
      },
      {
        title: '已派数量',
        dataIndex: 'sendNum',
      },
      { title: '操作', key: 'action', fixed: 'left', width: '150px' },
    ],
  };
</script>

<style lang="less" scoped>
  .padding {
    padding: 12px;
  }

  .back_color {
    background-color: hsl(0, 0%, 98%);
    position: relative;
  }

  .marginTop {
    margin-top: 12px;
  }
  .modelfooter {
    padding: 10px 16px;
    text-align: right;
    background: white;
    border-top: 1px solid rgb(240, 240, 240);
    border-radius: 0px 0px 2px 2px;
    position: absolute;
    bottom: 1px;
    width: 98%;
  }
</style>
