<template>
  <div style="min-height: 600px; overflow: auto">
    <div class="back_color" style="display: flex; justify-content: space-evenly">
      <div style="width: 49%; position: relative; padding: 12px 0 12px 12px">
        <a-form ref="formRef" :model="queryData1">
          <a-row>
            <a-col :span="5" style="margin-right: 12px">
              <a-form-item prop="productName">
                <a-input v-model:value="queryData1.toolNo" placeholder="请输入销售订单号" />
              </a-form-item>
            </a-col>
            <a-col :span="5" style="margin-right: 12px">
              <a-form-item prop="productName">
                <a-input v-model:value="queryData1.productName" placeholder="请输入产品名称" />
              </a-form-item>
            </a-col>
            <a-col style="margin-right: 12px">
              <a-button type="primary" size="middle" @click="getSalesOrder">查询</a-button>
            </a-col>
            <a-col style="margin-right: 12px">
              <a-button size="middle" @click="resetqueryData">重置</a-button>
            </a-col>
            <a-col style="margin-right: 12px">
              <a-button type="primary" size="middle" @click="incompleteQuery">未完成查询</a-button>
            </a-col>
            <a-col>
              <!-- <a-button size="middle" @click="onDetail(null)">排期></a-button> -->
            </a-col>
          </a-row>
          <a-table
            bordered
            :row-key="(record) => record.key"
            :loading="dataLoading"
            :columns="columns1"
            :data-source="SalesOrderData"
            :pagination="pagination1"
            :scroll="{ x: 1500, y: 400 }"
            :row-selection="{
              selectedRowKeys: saleselectedKeys,
              onChange: onSelectChange2,
              getCheckboxProps: getCheckboxProps,
              columnTitle: ' ',
            }"
          >
            <template #sale_date="{ record }">
              {{ record.sale_date ? record.sale_date.replace(' 00:00:00', '') : '' }}
            </template>
            <template #delivery_date="{ record }">
              {{ record.delivery_date ? record.delivery_date.replace(' 00:00:00', '') : '' }}
            </template>
            <template #sche_num="{ record }">
              <!-- 订单排期数量 -->
              {{ getScheNum(record.sale_id, record.material_id) }}
            </template>
          </a-table>
          <!-- <a-row class="aPagination">
            <a-pagination
              v-model:current="current1"
              :total="totals1"
              :pageSize="pageSize1"
              show-size-changer
              show-quick-jumper
              :show-total="(total: any) => `共 ${total} 条`"
              @change="onChange1"
              @showSizeChange="onChangeSize1"
            />
          </a-row> -->
        </a-form>
      </div>
      <div style="border-right: 2px solid #f0f0f0"></div>
      <div style="width: 49%; position: relative; padding: 12px 0">
        <a-form ref="formRef2" :model="queryData2">
          <a-row>
            <a-col :span="6" style="margin-right: 12px">
              <a-form-item prop="name">
                <a-input v-model:value="queryData2.name" placeholder="请输入产品名称" />
              </a-form-item>
            </a-col>
            <a-col style="margin-right: 12px">
              <a-button type="primary" size="middle" @click="getSchetoolListQuery">查询</a-button>
            </a-col>
            <a-col style="margin-right: 12px">
              <a-button size="middle" @click="resetqueryData2">重置</a-button>
            </a-col>
            <a-col style="position: absolute; right: 0">
              <!-- <a-button type="primary" size="middle" @click="handleAdd">新增</a-button> -->
              <a-button type="primary" size="middle" @click="onDetail(null)">新增排期</a-button>
            </a-col>
          </a-row>
        </a-form>
        <a-table
          bordered
          :row-key="(record) => record.id"
          :columns="columns2"
          :data-source="dataList"
          :loading="dataLoading"
          :pagination="pagination"
          :scroll="{ x: 1000, y: 400 }"
          :row-selection="{
            selectedRowKeys: selectedKeys,
            onChange: onSelectChange,
            getCheckboxProps: getDisCheckbox,
            columnTitle: ' ',
          }"
        >
          <template #onlineDate="{ record }">
            <!-- <a-date-picker
              v-model:value="record.onlineDate"
              placeholder="请选择时间"
              style="width: 100%"
              :valueFormat="format"
              :format="format"
              :showTime="format === 'YYYY-MM-DD'"
            /> -->
            <XjrDatePicker
              v-model:value="record.onlineDate"
              placeholder="请选择"
              :allowClear="true"
              :format="'YYYY-MM-DD'"
              style="width: 100%"
            />
          </template>
          <template #remark="{ record }">
            <a-input v-model:value="record.remark" placeholder="请输入内容" />
          </template>
          <template #operation="{ record }">
            <a-button type="link" @click="onDetail(record)">明细</a-button>
            <a-button type="text" danger @click="onDelete(record.id)">删除</a-button>
          </template>
        </a-table>
        <!-- <a-row class="aPagination">
          <a-pagination
            v-model:current="current2"
            :total="totals2"
            :pageSize="pageSize2"
            show-size-changer
            show-quick-jumper
            :show-total="(total: any) => `共 ${total} 条`"
            @change="onChange2"
            @showSizeChange="onChangeSize2"
          />
        </a-row> -->
      </div>
    </div>
  </div>
  <a-divider />
  <div style="text-align: right; padding: 0 12px 12px 0">
    <a-button @click="cancel">取消</a-button>
    <a-button @click="ok" type="primary" style="margin-left: 12px">确认</a-button>
  </div>

  <!-- 未完成查询 -->
  <a-modal
    :maskClosable="false"
    :title="titleModa3"
    v-model:visible="visibleModa3"
    :confirm-loading="confirmLoading"
    width="70%"
    :footer="null"
  >
    <query-modal :sche="sche" @cancel="submitCancel" @ok="submitOk"></query-modal>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, watch, reactive } from 'vue';
  import { getSalesOrderInfo } from '/@/api/mes/proschedule';
  import {
    getMesProSchetoolList,
    addMessaveBatch,
    deleteMesProSchetool,
  } from '/@/api/mes/schetool';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { XjrDatePicker } from '/@/components/DatePicker';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  const { notification } = useMessage();
  const { t } = useI18n();

  import QueryModal from './QueryModal.vue';

  const formRef = ref();
  const formRef2 = ref();

  const queryData1 = ref<any>({
    toolNo: '',
    productName: '',
  });

  const queryData2 = ref<any>({
    name: '',
  });

  const SalesOrderData = ref<any[]>([]);

  let props = defineProps(['scheId']);

  const scheId = { id: '' };

  const dataList = ref<any[]>([]);
  const dataListQuery = ref<any[]>([]);

  const dataLoading = ref<boolean>(false);
  const current2 = ref<number>(1);
  const pageSize2 = ref<number>(10);
  const totals2 = ref<number>(0);

  const current1 = ref<number>(1);
  const pageSize1 = ref<number>(10);
  const totals1 = ref<number>(0);

  const format = ref('YYYY-MM-DD');

  let selection = ref<any[]>([]);
  let tooDetailList = ref<any[]>([]);

  const gid = ref('');

  const cDate = ref('');

  const titleModa3 = ref('');
  const visibleModa3 = ref<boolean>(false);
  const confirmLoading = ref<boolean>(false);

  const sche = ref<any>({});

  const emit = defineEmits(['cancel', 'ok']);
  const saleselectedKeys = ref<string[]>([]);
  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);

  function getDisCheckbox(record: { id: any; code: any }) {
    return {
      disabled: !!selectedRowsData.value.find((item: any) => item?.id !== record.id),
    };
  }
  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
    //左侧产品选中：
    selection.value = [];
    saleselectedKeys.value = [];
    selectedRowsData.value[0]?.mesProSchetoolDetailList?.forEach((ele) => {
      saleselectedKeys.value.push(ele.saleId + '-' + ele.productId);

      console.log('ele====', ele);
      selection.value.push({
        checked: true,
        key: ele.saleId + '-' + ele.productId,
        id: ele.id,
        material_id: ele.productId,
        code: ele.productNo,
        name: ele.productName,
        customer_name: ele.customerName,
        sale_id: ele.saleId,
        sale_number: ele.saleNo,
        theme: ele.saleName,
        count: ele.saleNum,
        scheNum: ele.scheNum,
      });
    });
  }
  const cancel = () => {
    emit('cancel');
  };
  const ok = async () => {
    await addMessaveBatch({ list: dataList.value });
    notification.success({
      message: 'Tip',
      description: t('保存成功！'),
    });
    emit('ok', dataList.value);
  };

  function getScheNum(saleId, productId) {
    let num = 0;
    if (saleId && dataList.value) {
      console.log('getScheNum', dataList.value, saleId);
      dataList.value.forEach((item) => {
        if (item.mesProSchetoolDetailList)
          item.mesProSchetoolDetailList.forEach((e) => {
            if (e.saleId == saleId && e.productId == productId) num += parseInt(e.scheNum);
          });
      });
    }
    return num;
  }
  const columns1 = [
    {
      title: '#',
      align: 'center',
      fixed: 'left',
      width: 50,
      customRender: ({ index }: { index: number }) => {
        return `${(current1.value - 1) * pageSize1.value + index + 1}`;
      },
    },
    {
      title: '销售单号',
      dataIndex: 'sale_number',
      width: 120,
      sorter: true,
    },
    {
      title: '订单主题',
      dataIndex: 'theme',
      width: 100,
      sorter: true,
    },
    {
      title: '销售日期',
      dataIndex: 'sale_date',
      width: 100,
      sorter: true,
      slots: { customRender: 'sale_date' },
    },
    {
      title: '客户名称',
      dataIndex: 'customer_name',
      width: 120,
      sorter: true,
    },
    {
      title: '交付日期',
      dataIndex: 'delivery_date',
      width: 100,
      sorter: true,
      slots: { customRender: 'delivery_date' },
    },
    {
      title: '产品编码',
      dataIndex: 'code',
      width: 120,
      sorter: true,
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      width: 120,
      sorter: true,
    },
    {
      title: '订单数量',
      dataIndex: 'count',
      width: 120,
      sorter: true,
    },
    {
      title: '当前排期数量',
      dataIndex: 'sche_num',
      width: 120,
      sorter: true,
      slots: { customRender: 'sche_num' },
    },
    // {
    //   title: '未排期数量',
    //   dataIndex: 'no_sche_num',
    //   width: 120,
    //   sorter: true,
    //   slots: { customRender: 'no_sche_num' },
    // },
  ];

  const columns2 = [
    {
      title: '编号',
      dataIndex: 'id',
      sorter: true,
      width: 100,
    },
    {
      title: '上线日期',
      dataIndex: 'onlineDate',
      sorter: true,
      width: 130,
      slots: { customRender: 'onlineDate' },
    },
    {
      title: '产品编码',
      dataIndex: 'productNo',
      sorter: true,
      width: 100,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      sorter: true,
      width: 100,
    },
    {
      title: '排期数量',
      dataIndex: 'scheNum',
      sorter: true,
      width: 100,
    },
    {
      title: '制单日期',
      dataIndex: 'toolDate',
      sorter: true,
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sorter: true,
      width: 100,
      slots: { customRender: 'remark' },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 80,
      slots: { customRender: 'operation' },
    },
  ];

  //前端分页
  const pagination = reactive({
    // 表格分页的配置
    current: 1,
    pageSize: 10,
    showSizeChanger: true, // 用于控制展示每页多少条的下拉
    showQuickJumper: true,
    total: 0,
    pageSizeOptions: ['10', '20', '50', '100'],
    showTotal: (total) => `共 ${total} 条`,
    onShowSizeChange: pageSizeChange,
    onChange: pageChange,
    class: 'aPagination',
  });

  // 页数改变的方法

  function pageSizeChange(val, pageNum) {
    pagination.pageSize = pageNum; // 修改每页显示的条数
    pagination.current = 1;
  }
  // 点击上一页下一页的方法
  function pageChange(page, val) {
    console.log(page, val);
    pagination.current = page;
  }

  const pagination1 = reactive({
    // 表格分页的配置
    current: 1,
    pageSize: 10,
    showSizeChanger: true, // 用于控制展示每页多少条的下拉
    showQuickJumper: true,
    total: 0,
    pageSizeOptions: ['10', '20', '50', '100'],
    showTotal: (total) => `共 ${total} 条`,
    onShowSizeChange: pageSizeChange1,
    onChange: pageChange1,
    class: 'aPagination',
  });

  // 页数改变的方法

  function pageSizeChange1(val, pageNum) {
    pagination1.pageSize = pageNum; // 修改每页显示的条数
    pagination1.current = 1;
  }
  // 点击上一页下一页的方法
  function pageChange1(page, val) {
    console.log(page, val);
    pagination1.current = page;
  }
  //   const onChange1 = (pageNumber: number) => {
  //     console.log('Page: ', pageNumber);
  //     current1.value = pageNumber;
  //     getSalesOrder();
  //   };

  //   const onChange2 = (pageNumber: number) => {
  //     console.log('Page: ', pageNumber);
  //     current2.value = pageNumber;
  //     getSchetoolList();
  //   };

  //   const onChangeSize = (current: number, pageSize: number) => {
  //     console.log('pageSize: ', current, pageSize);
  //     pageSize1.value = pageSize;
  //     getSalesOrder();
  //   };
  //   const onChangeSize2 = (current: number, pageSize: number) => {
  //     console.log('pageSize: ', current, pageSize);
  //     pageSize2.value = pageSize;
  //     getSchetoolList();
  //   };
  const onDelete = (id: string) => {
    Modal.confirm({
      title: '提示信息',
      content: '是否确认删除？删除将不可恢复',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteMesProSchetool([id]).then((_) => {
          dataList.value = dataList.value.filter((item) => item?.id !== id);
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  };

  const onDetail = (record: any) => {
    if (record && record.id) {
      titleModa3.value = t('排期明细');
      sche.value = {
        id: record?.id,
        onlineDate: record?.onlineDate,
        remark: record?.remark,
        isQuery: false,
        list: record.mesProSchetoolDetailList,
      };
    } else {
      titleModa3.value = t('新增排期');
      if (!selection.value || selection.value.length == 0) {
        notification.warning({
          message: 'Tip',
          description: '请选择产品！',
        });
        return;
      }
      tooDetailList.value = [];
      selection.value.forEach((ele) => {
        tooDetailList.value.push({
          scheId: scheId.id,
          //   toolId: record.id,
          productId: ele.material_id,
          productNo: ele.code,
          productName: ele.name,
          customerName: ele.customer_name,
          saleId: ele.sale_id,
          saleNo: ele.sale_number,
          saleName: ele.theme,
          saleNum: ele.count,
        });
      });
      sche.value = {
        id: guid(),
        isQuery: false,
        list: tooDetailList.value,
      };
    }
    visibleModa3.value = true;
  };
  function onSelectChange2(selectedRowKeys: [], selectedRows) {
    saleselectedKeys.value = selectedRowKeys;
    selection.value = selectedRows;
    //勾选右侧产品时，如果左侧选择了则为更新：
    if (selectedRowsData && selectedRowsData.value?.length > 0) {
      dataList.value.forEach((item) => {
        if (selectedRowsData.value[0].id == item.id) {
          console.log('datalist=====i=', item, selection.value);
          item.scheId = scheId.id;
          item.productId = selection.value[0]?.material_id;
          item.productNo = selection.value[0]?.code;
          item.productName = selection.value[0]?.name;
          let oldlist = item.mesProSchetoolDetailList;
          item.mesProSchetoolDetailList = [];
          item.scheNum = 0;
          selection.value.forEach((ele) => {
            let scheNum = null;
            let id = null;
            oldlist?.forEach((old) => {
              if (old.productId == ele.material_id && old.saleId == ele.sale_id) {
                console.log('old=', old);
                id == old.id;
                scheNum = old.scheNum;
              }
            });
            item.scheNum = item.scheNum + scheNum;
            item.mesProSchetoolDetailList.push({
              id: id,
              scheId: scheId.id,
              toolId: item.id,
              productId: ele.material_id,
              productNo: ele.code,
              productName: ele.name,
              customerName: ele.customer_name,
              saleId: ele.sale_id,
              saleNo: ele.sale_number,
              saleName: ele.theme,
              saleNum: ele.count,
              scheNum: scheNum,
            });
          });
        }
      });
    }
  }

  function getCheckboxProps(record: { id: any; code: any }) {
    return {
      disabled: !!selection.value.find(
        (item: any) => item?.id !== record.id && item?.code !== record.code,
      ),
    };
  }
  const rowSelection = {
    onSelect: (_record: any, _selected: any, selectedRows: any) => {
      selection.value = selectedRows;
      saleselectedKeys.value = _record.key;
      console.log(selection.value, '勾选', _record);
    },

    getCheckboxProps: (record: { id: any; code: any }) => ({
      disabled: !!selection.value.find(
        (item: any) => item?.id !== record.id && item?.code !== record.code,
      ),
    }),
  };

  // 新增
  const handleAdd = () => {
    if (!selection.value || selection.value.length == 0) {
      gid.value = guid();
      cDate.value = getCurrentDate();
      const newData = {
        scheId: scheId.id,
        id: gid.value,
        onlineDate: '',
        productId: selection.value[0].material_id,
        productNo: selection.value[0].code,
        productName: selection.value[0].name,
        scheNum: '',
        toolDate: cDate.value,
        remark: '',
        mesProSchetoolDetailList: selection.value,
      };
      dataList.value.push(newData);
    } else {
      notification.warning({
        message: 'Tip',
        description: '请选择产品！',
      });
    }
  };

  const guid = () => {
    var res = '';
    for (var i = 0; i < 5; i++) {
      res += Math.floor(Math.random() * 5);
    }
    return new Date().getTime() + res;
  };

  const getCurrentDate = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();

    return year + '-' + month + '-' + day;
  };

  watch(
    () => props.scheId,
    (val) => {
      console.log('监听', val);
      if (val) {
        scheId.id = val.id;
        getSalesOrder();
        getSchetoolList();
      }
    },
  );

  onMounted(() => {
    scheId.id = props.scheId.id;
    getSalesOrder();
    getSchetoolList();
  });

  const getSalesOrder = async () => {
    const params = {
      //   limit: current1.value,
      //   size: 10000,
      saleNo: queryData1.value.toolNo,
      productName: queryData1.value.productName,
    };
    const data = await getSalesOrderInfo(params);
    SalesOrderData.value = data.list;
    totals1.value = Number(data.total);
  };

  const resetqueryData = () => {
    queryData1.value = {
      toolNo: '',
      productName: '',
    };
    getSalesOrder();
  };

  const resetqueryData2 = () => {
    queryData2.value = {
      name: '',
    };
    getSchetoolListQuery();
  };
  const getSchetoolListQuery = async () => {
    //查询产品，本地过滤数据
    if (dataListQuery.value && dataListQuery.value.length > 0) dataList.value = dataListQuery.value;
    if (queryData2.value.name) {
      dataListQuery.value = dataList.value;
      dataList.value = dataList.value.filter((e) => {
        if (e.productName && e.productName.indexOf(queryData2.value.name) >= 0) return true;
        else return false;
      });
    }
  };
  const getSchetoolList = async () => {
    const pageParams = {
      //   limit: current2.value, //当前页数
      //   size: pageSize2.value, //每页条数
      scheId: scheId.id,
      // productName: queryData2.value.name,
      needDetail: true, //查询子集
    };
    const res = await getMesProSchetoolList(pageParams);
    dataList.value = res;
    // totals2.value = res.total;
  };

  function incompleteQuery() {
    titleModa3.value = t('未完成查询');
    sche.value = {
      id: scheId.id,
      isQuery: true,
    };

    visibleModa3.value = true;
  }

  const submitCancel = () => {
    visibleModa3.value = false;
  };

  const submitOk = async (obj: any) => {
    if (obj.isQuery) {
      visibleModa3.value = false;
      return;
    }

    saleselectedKeys.value = [];
    selection.value = [];
    selectedKeys.value = [];
    selectedRowsData.value = [];
    let isExist = false;
    for (let i = 0; i < dataList.value.length; i++) {
      if (dataList.value[i].id == obj.id) {
        isExist = true;
        dataList.value[i].scheNum = obj.scheNum;
      }
    }
    if (!isExist) {
      cDate.value = getCurrentDate();
      console.log('obj.mesProSchetoolDetailList', obj.mesProSchetoolDetailList);
      const newData = {
        id: obj.id,
        scheId: scheId.id,
        onlineDate: obj.onlineDate,
        productId: obj.mesProSchetoolDetailList[0].productId,
        productNo: obj.mesProSchetoolDetailList[0].productNo,
        productName: obj.mesProSchetoolDetailList[0].productName,
        scheNum: obj.scheNum,
        toolDate: cDate.value,
        remark: obj.remark,
        mesProSchetoolDetailList: obj.mesProSchetoolDetailList,
      };
      dataList.value.push(newData);
    }

    visibleModa3.value = false;
  };
</script>
<style lang="less" scoped>
  .padding {
    padding: 12px;
  }

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

  .marginTop {
    margin-top: 12px;
  }

  .flex_center {
    display: flex;
    align-items: center;
  }

  .blue_line {
    width: 5px;
    height: 16px;
    background-color: #5e95ff;
    margin-right: 12px;
  }

  .aPagination {
    position: absolute;
    right: 0;
    bottom: 12px;
  }
</style>
