<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.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.materialNo }}</a-descriptions-item>
            <a-descriptions-item label="物料名称">{{ baseData1.materialName }}</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.planNum }}</a-descriptions-item>
            <a-descriptions-item label="单位">{{ baseData1.unity }} </a-descriptions-item>
            <a-descriptions-item label="生产订单号">{{ baseData1.orderNo }}</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.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">
            <a-form-item label="工单编号" name="workNo" required>
              <a-input
                v-model:value="formData.workNo"
                placeholder="请输入编码"
                :readonly="formData.isSysNum == '1'"
                :disabled="!rowData.isUpdate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="" name="isSysNum">
              <a-checkbox
                :disabled="!rowData.isUpdate"
                v-model:checked="formData.isSysNumBoolean"
                @change="handleSysChange"
              >
                用系统编号
              </a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item label="计划开工日期" name="planStartDate" required>
              <XjrDatePicker
                :disabled="!rowData.isUpdate"
                v-model:value="formData.planStartDate"
                placeholder="请选择"
                :allowClear="true"
                :format="'YYYY-MM-DD'"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="计划完工日期" name="planEndDate" required>
              <XjrDatePicker
                :disabled="!rowData.isUpdate"
                v-model:value="formData.planEndDate"
                placeholder="请选择"
                :allowClear="true"
                :format="'YYYY-MM-DD'"
                style="width: 100%"
              />
            </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>
  </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,
  } from '/@/api/mes/common';

  import { getMesProOrderplan } from '/@/api/mes/proorderplan';
  import {
    addMesProOrderwork,
    getMesProOrderwork,
    updateMesProOrderwork,
  } 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 { notification } = useMessage();
  const { t } = useI18n();
  let props = defineProps(['rowData']);
  const rowData: {
    id: string;
    planIds: string;
    isUpdate: boolean;
    flag: string;
  } = reactive({
    id: '',
    planIds: '',
    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;
  //   });
  // }
  // const renderSubFormList = async (list) => {
  //   detailList.value = [];
  //   list?.forEach((x) => {
  //     const dataObj = {};
  //     columnsProp.columns?.map((item) => {
  //       if (!item?.dataIndex) return;
  //       dataObj[item.dataIndex as string] = item.componentProps?.prestrainField
  //         ? x[item.componentProps.prestrainField]
  //         : null;
  //     });

  //     detailList.value.push(dataObj);
  //   });
  // };
  // const removeList = (index) => {
  //   detailList.value.splice(index, 1);
  // };
  // const baseData1 = ref<any>({});
  const formData = ref<any>({
    workNo: '',
    isSysNum: '',
    isSysNumBoolean: true,
    planStartDate: '',
    planEndDate: '',
    remark: '',
    priority: '',
  });

  const emit = defineEmits(['cancel', 'success']);
  const formRef = ref();
  onMounted(async () => {
    rowData.id = props.rowData.id;
    rowData.planIds = props.rowData.planIds;
    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('');
  });

  watch(
    () => props.rowData,
    (val) => {
      console.log('监听', val);
      if (val) {
        rowData.id = props.rowData.id;
        rowData.planIds = props.rowData.planIds;
        rowData.isUpdate = props.rowData.isUpdate;
        rowData.flag = props.rowData.flag;
        getDetailData();
      }
    },
  );
  const priorityOptions = ref<any[]>([]);
  const unityOptions = ref<any[]>([]);
  const carIdOptions = ref<any[]>([]);
  const lineIdOptions = ref<any[]>([]);
  const stepOptions = ref<any[]>([]);
  const planIdList = 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 = [];
    planIdList.value = rowData.planIds?.split(',');
    planIdList.value?.forEach(async (ele) => {
      const data = await getMesProOrderplan(ele);
      data.planId = data.id;
      data.id = '';
      baseDataList.value.push(data);
    });

    // console.log(data, '上部分信息');
    // baseData1.value = data;
    // formData.value.planId = data.id;
    if (!rowData.id) {
      formData.value.isSysNum = '1';
      handleSysChange();
    } else {
      const res = await getMesProOrderwork(rowData.id);
      if (res) {
        formData.value.id = res.id;

        formData.value.workNo = res.workNo;
        formData.value.isSysNum = res.isSysNum;
        formData.value.isSysNumBoolean = res.isSysNum == 1 ? true : false;
        formData.value.planStartDate = res.planStartDate;
        formData.value.planEndDate = res.planEndDate;
        formData.value.remark = res.remark;
      }
    }
  };
  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;
      }
      values.id = formData.value.id;
      values.isSysNum = formData.value.isSysNumBoolean ? '1' : '';
      console.log('values', values, formData.value, baseDataList);

      // TODO custom api
      if (!values.id) {
        //false 新增
        await addMesProOrderwork(values);
        notification.success({
          message: 'Tip',
          description: t('生成生产工单成功！'),
        }); //提示消息
      } else {
        await updateMesProOrderwork(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>
