<template>
  <div class="padding" style="height: 700px; overflow: auto">
    <div class="padding">
      <div style="font-weight: bold; font-size: 16px">工单信息</div>
      <div v-if="baseDataList">
        <div
          class="back_color padding marginTop"
          v-for="baseData1 in baseDataList"
          :key="baseData1.id"
        >
          <a-descriptions title="" :column="2">
            <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.scrafId">
                <span v-for="(re, i) in baseData1.scrafId.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>
        </div>
      </div>
    </div>

    <div class="padding">
      <div style="font-weight: bold; font-size: 16px">工单指派</div>
      <a-form ref="formRef" :model="formData" :labelCol="{ span: 6 }">
        <a-row>
          <a-col :span="12" v-show="false">
            <a-form-item label="班组ID" name="groupId" required>
              <a-input
                v-model:value="formData.groupId"
                placeholder="请选择"
                :disabled="!rowData.isUpdate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="班组编码" name="groupNo" required>
              <a-input
                v-model:value="formData.groupNo"
                placeholder="请选择"
                :disabled="!rowData.isUpdate"
                @click="multipleDialog = rowData.isUpdate ? true : false"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="班组名称" name="groupName" required>
              <a-input
                v-model:value="formData.groupName"
                :readonly="formData.isSysNum == '1'"
                :disabled="true"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-col :span="24">
          <a-form-item label="备注" name="remark" :labelCol="{ span: 3 }">
            <a-textarea
              :disabled="!rowData.isUpdate"
              v-model:value="formData.remark"
              placeholder="请输入"
              :auto-size="{ minRows: 2, maxRows: 5 }"
            />
          </a-form-item>
        </a-col>
      </a-form>
    </div>
    <a-divider />
    <div
      style="
        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%;
      "
      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="groupOptions"
          :columns="[
            {
              dataIndex: 'group_no',
              title: '班组编码',
              width: 150,
            },
            {
              dataIndex: 'group_name',
              title: '班组名称',
              width: 150,
            },
            {
              dataIndex: 'car_name',
              title: '所属车间',
              width: 150,
            },
            {
              dataIndex: 'line_name',
              title: '所属产线',
              width: 150,
            },
          ]"
          :row-selection="{
            selectedRowKeys: selectedKeys,
            onChange: onSelectChange,
            type: 'radio',
          }"
          :scroll="{ y: '300px' }"
        />
      </div>
      <div
        style="
          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%;
        "
        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>
    <!-- 
    <MultipleSelect
      v-if="multipleDialog"
      ref="MultipleSelectRef"
      v-model:multipleDialog="multipleDialog"
      datasourceType="api"
      :dicOptions="groupOptions"
      :apiConfig="{
        path: '/mes/getMesGoupList',
        method: 'GET',
        apiId: 'copy1692322438121d88503',
        apiParams: [
          {
            key: '1',
            title: 'Query Params',
            tableInfo: [],
          },
          { key: '2', title: 'Header', tableInfo: [] },
          { key: '3', title: 'Body' },
        ],
        outputParams: [
          {
            name: 'group_no',
            tableTitle: '班组编码',
            bindField: 'group_no',
            show: true,
            width: 150,
          },
          {
            name: 'group_name',
            tableTitle: '班组名称',
            bindField: 'group_name',
            show: true,
            width: 150,
          },
          {
            name: 'car_name',
            tableTitle: '所属车间',
            bindField: 'car_name',
            show: true,
            width: 150,
          },
          {
            name: 'line_name',
            tableTitle: '所属产线',
            bindField: 'line_name',
            show: true,
            width: 150,
          },
        ],
      }"
      @submit="renderSubFormList"
      popupType="associate"
    /> -->
  </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,
    getAutoCode,
    getMesFactoryListByType,
    getProcessTechList,
    getMesGoupList,
  } from '/@/api/mes/common';

  import { getMesProOrderwork, updateMesProOrderworkList } from '/@/api/mes/proorderwork';
  // import SelectUser from '/@/components/Form/src/components/SelectUser.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 { notification } = useMessage();
  const { t } = useI18n();
  let props = defineProps(['rowData']);
  const rowData: {
    id: string;
    workIds: string;
    isUpdate: boolean;
    flag: string;
  } = reactive({
    id: '',
    workIds: '',
    isUpdate: false,
    flag: '',
  });

  // const detailList = 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);
    formData.value.groupId = '';
    formData.value.groupNo = '';
    formData.value.groupName = '';
    selectedRowsData.value.forEach((ele) => {
      formData.value.groupId = ele.id;
      formData.value.groupNo = ele.group_no;
      formData.value.groupName = ele.group_name;
    });
    multipleDialog.value = false;
  }
  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.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.workIds = props.rowData.workIds;
    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.workIds = props.rowData.workIds;
        rowData.isUpdate = props.rowData.isUpdate;
        rowData.flag = props.rowData.flag;
        formData.value = {};
        getDetailData();
      }
    },
  );
  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[]>([]);

  async function handleSysChange() {
    console.log('chg===', rowData, formData, formData.value.isSysNumBoolean);
    if (!rowData.isUpdate) return;

    if (formData.value.isSysNumBoolean) {
      formData.value.workNo = await getAutoCode('mesProOrderWorkNo');
      formData.value.isSysNum = '1';
    } else {
      formData.value.workNo = '';
      formData.value.isSysNum = '';
    }
  }
  const getDetailData = async () => {
    baseDataList.value = [];
    workIdList.value = rowData.workIds?.split(',');
    workIdList.value?.forEach(async (ele) => {
      const data = await getMesProOrderwork(ele);
      baseDataList.value.push(data);
    });
  };
  async function handleSubmit() {
    try {
      let values = await formRef.value?.validate();
      values.planList = baseDataList.value;
      if (!values.planList || values.planList.length == 0) {
        notification.error({
          message: 'Tip',
          description: t('生产工单不能为空'),
        });
        return;
      }

      console.log('values', values, formData.value, baseDataList);

      await updateMesProOrderworkList(values);
      notification.success({
        message: 'Tip',
        description: t('指派生产工单成功！'),
      }); //提示消息
      // formRef.value.resetFields();
      emit('success');
    } finally {
    }
  }

  function handleClose() {
    emit('cancel');
  }
</script>

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

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

  .marginTop {
    margin-top: 12px;
  }
</style>
