<template>
  <PageWrapper dense contentFullHeight fixedHeight class="bg-white pl-4">
    <a-row>
      <a-col :span="12" class="top-left">
        <div class="label">排产选项</div>
        <a-checkbox-group v-model:value="optionValue">
          <a-checkbox value="优先白班">优先白班</a-checkbox>
          <a-checkbox value="避开节假日">避开节假日</a-checkbox>
          <a-checkbox value="可安排加班">可安排加班</a-checkbox>
        </a-checkbox-group>
      </a-col>
      <a-col :span="12" class="top-right">
        <div class="right-input">
          <div class="label">其他要求</div>
          <XjrInput v-model:value="requireValue" placeholder="请输入其他要求" isShowAi />
        </div>
        <a-button type="primary" @click="sendAi">智能排产</a-button>
      </a-col>
    </a-row>
    <a-divider />
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1" tab="基础数据" class="tab-left">
        <div class="font-bold">订单数据</div>
        <BasicTable @register="registerOrderTable" />
        <a-row :gutter="16" class="mt-5">
          <a-col :span="12">
            <div class="font-bold">排班信息</div>
            <BasicTable @register="registerGroupTable" />
          </a-col>
          <a-col :span="12">
            <div class="font-bold">产线信息</div>
            <BasicTable @register="registerLineTable" />
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane key="2" tab="工单信息">
        <BasicTable @register="registerWorkOrderTable" />
      </a-tab-pane>
    </a-tabs>
  </PageWrapper>
  <LoadingBox v-if="spinning" />
</template>
<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import { getAiProData, getScheduling } from '/@/api/aiCreateTable';
  import { PageWrapper } from '/@/components/Page';
  import { XjrInput } from '/@/components/Input';
  import { LoadingBox } from '/@/components/ModalPanel/index';

  const orderColumns: BasicColumn[] = [
    {
      title: '订单号',
      dataIndex: 'orderNum',
      align: 'center',
      resizable: true,
    },

    {
      title: '产品编码',
      dataIndex: 'orderCode',
      align: 'center',
      resizable: true,
    },
    {
      title: '产品名称',
      dataIndex: 'orderName',
      align: 'center',
      resizable: true,
    },
    {
      title: '规格型号',
      dataIndex: 'orderModel',
      align: 'center',
      resizable: true,
    },
    {
      title: '需求数量',
      dataIndex: 'orderCount',
      align: 'center',
      resizable: true,
    },
    {
      title: '下单日期',
      dataIndex: 'placeOrderDate',
      align: 'center',
      resizable: true,
    },
    {
      title: '交期',
      dataIndex: 'completeOrderDate',
      align: 'center',
      resizable: true,
    },
  ];

  const groupColumns: BasicColumn[] = [
    {
      title: '班组编码',
      dataIndex: 'groupCode',
      align: 'center',
      resizable: true,
    },

    {
      title: '班组名称',
      dataIndex: 'groupName',
      align: 'center',
      resizable: true,
    },
    {
      title: '班组类型',
      dataIndex: 'groupType',
      align: 'center',
      resizable: true,
    },
    {
      title: '工作时段',
      dataIndex: 'groupDate',
      align: 'center',
      resizable: true,
    },
    {
      title: '工作时长',
      dataIndex: 'workTime',
      align: 'center',
      resizable: true,
    },
  ];

  const lineColumns: BasicColumn[] = [
    {
      title: '车间名称',
      dataIndex: 'lineName',
      align: 'center',
      resizable: true,
    },

    {
      title: '产品名称',
      dataIndex: 'productName',
      align: 'center',
      resizable: true,
    },
    {
      title: '适配类型',
      dataIndex: 'adaptationModel',
      align: 'center',
      resizable: true,
    },
    {
      title: '每小时产能',
      dataIndex: 'oneHourCapacity',
      align: 'center',
      resizable: true,
    },
  ];

  const workOrderColumns: BasicColumn[] = [
    {
      title: '工单号',
      dataIndex: 'orderNum',
      align: 'center',
      resizable: true,
    },

    {
      title: '日期',
      dataIndex: 'date',
      align: 'center',
      resizable: true,
    },
    {
      title: '加工数量',
      dataIndex: 'quantity',
      align: 'center',
      resizable: true,
    },
    {
      title: '班组',
      dataIndex: 'team',
      align: 'center',
      resizable: true,
    },
    {
      title: '产品编码',
      dataIndex: 'productionCode',
      align: 'center',
      resizable: true,
    },
    {
      title: '产品名称',
      dataIndex: 'productionName',
      align: 'center',
      resizable: true,
    },
    {
      title: '车间名称',
      dataIndex: 'workshopName',
      align: 'center',
      resizable: true,
    },
  ];

  const orderInfo = {
    orderNum: '订单号',
    orderCode: '产品编码',
    orderName: '产品名称',
    orderModel: '规格型号',
    orderCount: '需求数量',
    placeOrderDate: '下单日期',
    completeOrderDate: '交期',
  };
  const groupInfo = {
    groupCode: '班组编码',
    groupName: '班组名称',
    groupType: '班组类型',
    groupDate: '工作时段',
    workTime: '工作时长',
  };
  const lineInfo = {
    lineName: '车间名称',
    productName: '产品名称',
    adaptationModel: '适配类型',
    oneHourCapacity: '每小时产能',
  };
  const workOrderInfo = {
    工单号: 'orderNum',
    日期: 'date',
    加工数量: 'quantity',
    班组: 'team',
    产品编码: 'productionCode',
    产品名称: 'productionName',
    车间名称: 'workshopName',
  };

  const activeKey = ref('1');
  const optionValue = ref(['优先白班']);
  const requireValue = ref('');
  const spinning = ref<boolean>(false);

  const [registerOrderTable, { getSelectRows: getOrderRows }] = useTable({
    api: getAiProData,
    rowKey: 'id',
    columns: orderColumns,
    striped: false,
    showTableSetting: false,
    pagination: false,
    fetchSetting: {
      listField: 'orderDataList',
    },
    rowSelection: {
      type: 'checkbox',
    },
  });

  const [registerGroupTable, { getSelectRows: getGroupRows }] = useTable({
    api: getAiProData,
    rowKey: 'id',
    columns: groupColumns,
    striped: false,
    showTableSetting: false,
    pagination: false,
    fetchSetting: {
      listField: 'groupDataList',
    },
    rowSelection: {
      type: 'checkbox',
    },
  });

  const [registerLineTable, { getSelectRows: getLineRows }] = useTable({
    api: getAiProData,
    rowKey: 'id',
    columns: lineColumns,
    striped: false,
    showTableSetting: false,
    pagination: false,
    fetchSetting: {
      listField: 'lineDataList',
    },
    rowSelection: {
      type: 'checkbox',
    },
  });

  const [registerWorkOrderTable, { setProps }] = useTable({
    dataSource: [],
    rowKey: 'id',
    columns: workOrderColumns,
    striped: false,
    showTableSetting: false,
    pagination: false,
  });

  const changeData = (selectedData, infoData) => {
    const data: any[] = [];
    if (selectedData.length) {
      selectedData.forEach((item) => {
        const info = {};
        Object.keys(item).forEach((key) => {
          if (infoData[key]) {
            info[infoData[key]] = item[key];
          }
        });
        data.push(info);
      });
    }
    return data;
  };

  const sendAi = async () => {
    spinning.value = true;
    const orderData = changeData(getOrderRows(), orderInfo);
    const lineData = changeData(getLineRows(), lineInfo);
    const groupData = changeData(getGroupRows(), groupInfo);

    const message = `请帮我根据订单数据、产线数据、排班数据做工单排产，订单数据为：data=${JSON.stringify(
      orderData,
    )}，产线数据为：data=${JSON.stringify(lineData)}，排班数据为：data=${JSON.stringify(
      groupData,
    )}，要求${optionValue.value.toString()}，请帮我返回工单json，工单json格式如下：[ {"工单号": "W001", "日期": "2025-02-08", "加工数量": 320, "班组": "1组白班", "产品编码": "STU01", "产品名称": "8#变速齿轮", "车间名称": "W0001","已加工数量":"320"},{ "工单号": "W002", "日期": "2025-02-09","加工数量": 320, "班组": "1组白班","产品编码": "STU01", "产品名称": "8#变速齿轮", "车间名称": "W0001","已加工数量":"640" }],工单数据存在多条，在这串json中，工单号是递增的，日期是在订单下单日期起之后递增，班组是选择的班组数据，在订单需求数量在交单日期完成前能完成的时候就优先白班，完不成就增加夜班排班，加工数量是选择的产线的每小时产能和选择的班组工作时间的乘积，产品编码是所选订单的产品编码，产品名称为订单数据的产品名称，车间名称是所选车间的名称优先产能高的车间，已加工数量是选择的订单需求数量是选择订单的工单的加工数量之和，注意最后一条工单的已加工总数等于前面工单加工数量之和且必须大于订单的需求总数，且必须在订单数据的交单日期前完成订单所需的需求总数。注意最后返回的数据不需要任何分析过程，只需要工单json。`;
    try {
      const res = await getScheduling({ question: message, otherRequire: requireValue.value });
      if (res) {
        const workShopData = Array.isArray(JSON.parse(res)) ? JSON.parse(res) : [JSON.parse(res)];
        const dataSource = changeData(workShopData, workOrderInfo);
        activeKey.value = '2';
        nextTick(() => {
          setProps({
            dataSource,
          });
        });
      }
    } catch (e) {}

    spinning.value = false;
  };
</script>
<style lang="less" scoped>
  :deep(.vben-page-wrapper-content) {
    overflow: auto;
    display: flex;
    flex-direction: column;
  }

  .tab-left {
    :deep(.vben-basic-table) {
      height: 250px;
    }
  }

  :deep(.ant-tabs) {
    margin-right: 16px;
  }

  :deep(.ant-tabs-content-holder) {
    overflow: auto;
  }

  .top-left {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }

  .top-right {
    display: flex;
    align-items: end;

    .right-input {
      width: 500px;
      margin-right: 10px;
    }
  }

  .label {
    line-height: 35px;
  }

  :deep(.ant-divider) {
    margin-bottom: 10px;
  }
</style>
