<template>
  <div class="padding" style="height: 700px; overflow: auto">
    <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="orderNo" required>
              <a-input
                v-model:value="formData.orderNo"
                placeholder="请输入编码"
                :readonly="formData.isSysNum == '1'"
                :disabled="!rowData.isUpdate || rowData.id.length > 0"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="" name="isSysNum">
              <a-checkbox
                :disabled="!rowData.isUpdate || rowData.id.length > 0"
                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="priority" required>
              <a-select
                :options="priorityOptions"
                placeholder="请选择"
                v-model:value="formData.priority"
                :disabled="!rowData.isUpdate"
                allowClear
              >
              </a-select>
            </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>
    <div class="padding">
      <div style="font-weight: bold; font-size: 16px">产品信息</div>

      <div style="float: right">
        <a-button type="primary" @click="multipleDialog = true" class="select-btn">选择 </a-button>
      </div>
      <a-table
        :columns="filterColum(columnsProp.columns)"
        :bordered="true"
        :pagination="false"
        :data-source="detailList"
        :scroll="{ x: 'max-content' }"
      >
        <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
              v-if="!record.state || record.state == '1'"
              title="删除"
              @click="removeList(index, record)"
            >
              <MinusCircleOutlined style="padding-bottom: 20px" />
            </a>
          </template>
          <template v-if="column.dataIndex === 'planNum'">
            <a-input-number
              :min="0"
              :max="record.saleNum"
              :step="1"
              :disabled="!rowData.isUpdate || !(!record.state || record.state == '1')"
              v-model:value="record.planNum"
              placeholder="请输入"
            />
          </template>
          <template v-if="column.dataIndex === 'onlineDate'">
            <!-- {{ record.onlineDate }}
            <a-date-picker
              :disabled="!rowData.isUpdate || !(!record.state || record.state == '1')"
              v-model:value="record.onlineDate"
              placeholder="请选择"
            /> -->
            <XjrDatePicker
              v-model:value="record.onlineDate"
              placeholder="请选择"
              :allowClear="true"
              :format="'YYYY-MM-DD'"
              :disabled="!rowData.isUpdate || !(!record.state || record.state == '1')"
            />
          </template>
        </template>
      </a-table>
      <MultipleSelect
        v-if="multipleDialog"
        ref="MultipleSelectRef"
        v-model:multipleDialog="multipleDialog"
        :params="{ itemId }"
        :datasourceType="columnsProp.preloadType"
        :dicOptions="columnsProp.dicOptions"
        :apiConfig="columnsProp.apiConfig"
        :isSubFormUse="true"
        @submit="renderSubFormList"
        popupType="preload"
      />
    </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 } from '/@/api/mes/common';

  import {
    addMesProOrder,
    getMesProOrder,
    updateMesProOrder,
    deleteMesProOrder,
  } from '/@/api/mes/proorder';
  // import SelectUser from '/@/components/Form/src/components/SelectUser.vue';
  import AutoCodeRule from '/@/components/Form/src/components/AutoCodeRule.vue';
  import { MultipleSelect } from '/@/components/MultiplePopup';
  import { XjrDatePicker } from '/@/components/DatePicker';
  // 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;
    orderId: string;
    isUpdate: boolean;
    flag: string;
  } = reactive({
    id: '',
    orderId: '',
    isUpdate: false,
    flag: '',
  });
  const columnsProp = {
    mainKey: 'mesProOrderDetailList',
    columns: [
      {
        key: '33c983ef96f14512bb55a86943992152',
        title: '销售单号ID',
        dataIndex: 'saleOrderId',
        componentType: 'AssociateSelect',
        show: false,
        componentProps: {
          prestrainField: 'sale_id',
        },
      },
      {
        key: '98748f978a2b4e01adbdb82cba77bdfa',
        title: '销售单号',
        dataIndex: 'saleOrderNo',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'sale_number',
        },
      },
      {
        key: 'be896e7f9d734bf4a478909bb16471fb',
        title: '产品编码',
        dataIndex: 'productNo',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'code',
        },
      },
      {
        key: 'b7cbb6c8c133465a849578b765a03f89',
        title: '产品ID',
        dataIndex: 'productId',
        componentType: 'AssociateSelect',
        show: false,
        componentProps: {
          prestrainField: 'material_id',
        },
      },
      {
        key: 'b895da75e830495c8d4ff0a425e8e687',
        title: '产品名称',
        dataIndex: 'productName',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'name',
        },
      },
      {
        key: '37fb118c17544118be39dc4ea01e1d1e',
        title: '规格型号',
        dataIndex: 'speModel',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'model',
        },
      },
      {
        key: '23cbed159a7749659f500992e0d46933',
        title: '单位',
        dataIndex: 'unity',
        componentType: 'Input',
        defaultValue: '',
        componentProps: {
          prestrainField: 'unit_name',
        },
      },
      {
        key: '09f6b12c5176483b88044d318f13d807',
        title: '销售数量',
        dataIndex: 'saleNum',
        componentType: 'InputNumber',
        show: false,
        componentProps: {
          prestrainField: 'count',
        },
      },
      {
        key: '09f6b12c5176483b88044d318f13d807',
        title: '计划产量',
        dataIndex: 'planNum',
        componentType: 'InputNumber',
        componentProps: {
          prestrainField: 'count',
        },
      },
      {
        key: '978b5193ff4b43d6ab8132df92661578',
        title: '上线日期',
        dataIndex: 'onlineDate',
        componentType: 'DatePicker',
        defaultValue: '',
        componentProps: {},
      },
      { title: '操作', key: 'action', fixed: 'right', width: '50px' },
    ],
    buttonName: '选择',
    showIndex: false,
    useSelectButton: true,
    useAddButton: false, //不显示新增按钮
    preloadType: 'api',
    showLabel: true,
    itemId: '',
    multipleHeads: [],
    dicOptions: [],
    showComponentBorder: true,
    apiConfig: {
      path: '/mes/getSaleOrderProductList',
      method: 'GET',
      apiId: 'copy1691460260596d60862',
      apiParams: [
        {
          key: '1',
          title: 'Query Params',
          tableInfo: [
            {
              name: 'keyword',
              value: null,
              description: null,
              required: false,
              dataType: 'String',
              type: null,
              defaultValue: null,
              validateType: null,
              error: null,
              expression: null,
              children: null,
              bindType: '',
            },
            {
              name: 'showLabel',
              value: '',
              description: '回显字段',
              required: false,
              dataType: 'String',
              type: null,
              defaultValue: 'code',
              validateType: null,
              error: null,
              expression: null,
              children: null,
              bindType: '',
            },
            {
              name: 'queryType',
              value: null,
              description: '查询类型',
              required: false,
              dataType: 'String',
              type: null,
              defaultValue: null,
              validateType: null,
              error: null,
              expression: null,
              children: null,
              bindType: '',
            },
            {
              name: 'sale_id',
              value: '',
              description: '销售订单ID',
              required: false,
              dataType: 'String',
              type: null,
              defaultValue: null,
              validateType: null,
              error: null,
              expression: null,
              children: null,
              bindType: '',
            },
          ],
        },
        { key: '2', title: 'Header', tableInfo: [] },
        { key: '3', title: 'Body' },
      ],
      script:
        'var condition="";\r\nif(sale_id!=null&&sale_id!=""){ \r\n    condition+=" and sale_id=#{sale_id}";\r\n}\r\nreturn db.select("SELECT t.id AS `key` ,t.id AS `value`,t.code AS label,t.* FROM case_erp_sale_detail t where 1=1  "+condition)',
      outputParams: [
        { tableTitle: '销售单号', name: 'sale_number' },
        { tableTitle: '销售主题', name: 'theme' },
        { tableTitle: '产品编码', name: 'code' },
        { tableTitle: '产品名称', name: 'name' },
        { tableTitle: '规格型号', name: 'model' },
        { tableTitle: '单位', name: 'unit_name' },
        { tableTitle: '订单数量', name: 'count' },
      ],
    },
    showFormBorder: true,
    span: '24',
  };
  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;
      });

      //判断是否存在。
      let exist = false;
      detailList.value.forEach((e) => {
        // console.log(JSON.stringify(e), JSON.stringify(dataObj));
        if (JSON.stringify(e) == JSON.stringify(dataObj)) exist = true;
      });
      if (!exist) detailList.value.push(dataObj);
    });
  };
  // const removeList = (index) => {
  //   detailList.value.splice(index, 1);
  // };
  function removeList(index, record: Recordable) {
    if (!record.id) {
      detailList.value.splice(index, 1);
      return;
    }

    Modal.confirm({
      title: '提示信息',
      content: '是否确认删除？删除将不可恢复',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteMesProOrder([record.id]).then((_) => {
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
          detailList.value.splice(index, 1);
        });
      },
      onCancel() {},
    });
  }

  const baseData1 = ref<any>({});
  const formData = ref<any>({
    isSysNumBoolean: true,
    isSysNum: '1',
    orderNo: '',
    remark: '',
    priority: '',
  });

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

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

    if (formData.value.isSysNumBoolean) {
      formData.value.orderNo = await getAutoCode('mesproOrderNo');
      formData.value.isSysNum = '1';
    } else {
      formData.value.orderNo = '';
      formData.value.isSysNum = '';
    }
  }
  const getDetailData = async () => {
    if (!rowData.id) {
      detailList.value = [];
      formData.value.id = '';
      formData.value.isSysNum = '1';
      formData.value.isSysNumBoolean = true;
      handleSysChange();
      //查询明细记录
      // if (formData.value.productId)
    } else {
      const res = await getMesProOrder(rowData.id);
      if (res) {
        formData.value.id = res.id;
        formData.value.isSysNum = res.isSysNum;
        formData.value.isSysNumBoolean = res.isSysNum == 1 ? true : false;
        formData.value.orderNo = res.orderNo;
        formData.value.priority = res.priority;
        formData.value.remark = res.remark;
        detailList.value = res.mesProOrderDetailList;
      }
    }
  };
  async function handleSubmit() {
    try {
      let values = await formRef.value?.validate();
      // values.orderId = formData.value.orderId;
      // values.orderNo = formData.value.orderNo;
      // values.remark = formData.value.remark;

      values.id = formData.value.id;
      values.isSysNum = formData.value.isSysNumBoolean ? '1' : '';
      if (!detailList.value || detailList.value.length == 0) {
        notification.error({
          message: 'Tip',
          description: t('产品明细不能为空'),
        });
        return;
      }
      values.mesProOrderDetailList = detailList.value;
      console.log('values', values, formData.value, baseData1);

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