<template>
  <div class="shipping-bill-container">
    <!-- 查询区域 -->
    <div class="jeecg-basic-table-form-container">
      <a-spin :spinning="sandCarLoading">
        <a-form layout="inline" ref="form" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-row :gutter="24" class="form-row">
            <!-- <a-col :span="4">
              <a-form-item label="铸机">
                <segmented-select v-model:value="queryParam.ccmNo" dict="lg_zj" @change="changeType" defaultValue="5" />
              </a-form-item>
            </a-col> -->
            <!-- <a-col :span="6">
              <a-form-item label="钢种">
                <a-input v-model:value="queryParam.steel" placeholder="请输入" allowClear />
              </a-form-item>
            </a-col> -->
            <!-- <a-col :span="6">
              <a-form-item label="规格">
                <JSearchSelect placeholder="请选择" v-model:value="queryParam.spec" dict="billet_spec" allowClear />
              </a-form-item>
            </a-col> -->
            <!-- <a-col :xl="4">
              <a-form-item label="班组">
                <JSearchSelect placeholder="请选择" v-model:value="queryParam.shiftGroup" dict="lg_bz" @change="editQueryParam" allowClear />
              </a-form-item>
            </a-col>
            <a-col :xl="4">
              <a-form-item label="班别">
                <JSearchSelect placeholder="请选择" v-model:value="queryParam.shift" dict="lg_bb" @change="editQueryParam" allowClear />
              </a-form-item>
            </a-col> -->
            <a-col :span="4">
              <a-form-item label="车号">
                <JSearchSelect placeholder="请选择" v-model:value="queryParam.licensePlate" dict="lg_car" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="类型">
                <JSearchSelect placeholder="请选择" v-model:value="queryParam.btype" :defaultValue="0" dict="lg_btype" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="定尺">
                <JSearchSelect type="list" v-model:value="queryParam.size" dict="lg_dcgg" placeholder="请选择" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="目的地">
                <JSearchSelect
                  v-model:value="queryParam.destination"
                  :options="destinationOptions[queryParam.ccmNo]"
                  placeholder="请选择"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :span="4" v-if="queryParam.ccmNo === '6'">
              <a-form-item label="车位号">
                <a-select style="width: 100%" v-model:value="queryParam.positionNum" placeholder="请选择" :options="carPosition6" />
              </a-form-item>
            </a-col>
            <a-col :span="4" v-else>
              <a-form-item label="车位号">
                <a-select style="width: 100%" v-model:value="queryParam.positionNum" placeholder="请选择" :options="carPosition5" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24" style="text-align: center; margin-bottom: 20px">
              <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </div>

    <!--引用表格-->
    <BasicTable @register="registerTable" class="shipping-bill-talbe" :rowSelection="rowSelection">
      <template #form-positionNum="{ model, field }">
        <a-radio-group v-model:value="model[field]" button-style="solid" @change="() => reload()">
          <a-radio-button value="1" v-if="Number(machine) === 5">1号车位</a-radio-button>
          <a-radio-button value="2">2号车位</a-radio-button>
          <a-radio-button value="3" v-if="Number(machine) === 6">3号车位</a-radio-button>
          <a-radio-button value="4">4号车位</a-radio-button>
        </a-radio-group>
      </template>

      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="batchHandleDelete" :disabled="!selectedRowKeys.length" preIcon="ant-design:delete-outlined">
          批量删除
        </a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <template #billXuhao="{ record }">{{ record.uniqueCode || '' }}</template>
      <template #licensePlate="{ record }">
        <a-badge-ribbon style="top: -20px" v-if="record.licensePlateStatus === 1" color="red" text="错误">
          <JSearchSelect
            type="list"
            v-model:value="record.licensePlate"
            dict="lg_car"
            :getPopupContainer="
              () => {
                return documentBody;
              }
            "
            @change="(v) => handleLicensePlateChange(v, record)"
            placeholder="请选择"
            allowClear
          />
        </a-badge-ribbon>
        <div v-else>{{ record.licensePlate }}</div>
      </template>
      <template #btype="{ record }">
        <a-switch
          v-model:checked="record.btype"
          checked-value="0"
          @change="(checked) => handleBtypeChange(checked, record)"
          checked-children="热坯"
          un-checked-value="1"
          un-checked-children="冷坯"
        />
      </template>
      <template #destination="{ record }">
        <JSearchSelect
          v-if="Number(record.typeConfigId) === 1024"
          type="list"
          v-model:value="record.destinationId"
          :disabled="Number(record.typeConfigId) !== 1024"
          :options="destinationOptions[record.ccmNo]"
          placeholder="请选择"
          allowClear
          @change="(v) => handleDestinationIdChange(v, record)"
        />
        <div v-else>{{ record.destination }}</div>
      </template>
      <template #outTime="{ record }">
        <a-date-picker
          style="padding: 4px 2px"
          show-time
          placeholder="选择发车时间"
          v-model:value="record.outTimeDate"
          @ok="(v) => onOkOutTime(v, record)"
        />
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <!-- 编辑 -->
    <editModal ref="modelRef" @ok="formSubmitSuccess" />
    <!-- 日志 -->
    <logModel ref="logRef" @ok="handleSuccess"></logModel>
    <!-- 详情  -->
    <detailsModal @register="registerDetailModal" showActionColumn @success="handleSuccess" />
    <!-- 热装 -->
    <rod-line
      @register="registerRodLineModal"
      @success="handleSuccess"
      :machine="queryParam.ccmNo"
      :machineConfig="machineConfigs()[MachineConfigType.RODLINE]"
    />
    <!-- 堆垛装车 -->
    <stack @register="registerStackingEntruckingModal" :machine="queryParam.ccmNo" @success="handleSuccess" />
    <!-- 打印 -->
    <printModal @register="registerPrintModal" @success="handleSuccess" />
    <!-- 修改目的地 -->
    <a-modal v-model:open="openTypeConfigIdModal" title="切换目的地" centered width="400px" :footer="null">
      <div class="flex justify-center items-center" style="padding: 20px">
        <div>选择目的地：</div>
        <JSearchSelect
          type="list"
          style="width: 200px"
          v-model:value="currentRecord.destinationId"
          :options="destinationOptions[currentRecord.ccmNo]"
          placeholder="请选择"
          allowClear
          @change="(v) => handleDestinationIdChange(v, currentRecord)"
        />
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" name="shippingBill" setup>
  // import SegmentedSelect from '/@/components/SegmentedSelect/index.vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, initDictConfig, queryParam, searchFormSchema, carPosition6, carPosition5 } from './shippingBill.data';
  import { deleteOne, batchDelete, edit, destinationSwitch } from './shippingBill.api';
  import { defHttp } from '/@/utils/http/axios';
  import { onMounted, ref, reactive, h } from 'vue';
  // import hotDeliveryModal from './components/hotDeliveryModal.vue';
  import editModal from './components/editModal.vue';
  import logModel from './components/logModel.vue';
  import detailsModal from './components/detailsModal.vue';
  import printModal from './components/printModal.vue';
  import { useModal } from '/@/components/Modal';
  import { message } from 'ant-design-vue';
  import { destinationOptions, getMachineConfig, MachineConfigType, getMachineNum } from '../hotDelivery/common.data';
  import rodLine from './components/hotCharging/rodLine.vue';
  import stack from './components/hotCharging/stack.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import dayjs from 'dayjs';

  const { createConfirm } = useMessage();

  const sandCarLoading = ref(false);
  const logRef = ref();
  const documentBody = document.body;
  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 6 },
  });
  const modelRef = ref();
  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 18 },
  });
  const machine = getMachineNum();
  queryParam.value.ccmNo = machine;
  queryParam.value.positionNum = Number(machine) === 5 ? '1' : '2';

  // 六号机配置信息
  const machineConfigs = () => getMachineConfig(queryParam.value.ccmNo);

  // 棒线堆垛明细
  const [registerDetailModal, { openModal: openDetailModal }] = useModal();
  // 注册添加棒线弹框
  const [registerRodLineModal, { openModal: openRodLineModal }] = useModal();
  // 注册打印modal
  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  // 堆垛发车modal
  const [registerStackingEntruckingModal, { openModal: openStackingEntruckingModal }] = useModal();

  // 发车
  const sendCar = async (record) => {
    try {
      setLoading(true);
      await defHttp.post({ url: '/storageBill/startCar', params: { ...record } }, { joinParamsToUrl: true });
      reload();
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 操作栏
   */
  function getTableAction(record) {
    let actions: any[] = [];
    if (!!record.outTime || !!record.arrivalTime) {
      actions = [
        {
          label: '发车',
          disabled: !!record.outTime || !record.destination,
          icon: 'ant-design:car-outlined',
          popConfirm: {
            title: '是否确认发车？',
            description: record.amountTotal <= 0 ? `注意：当前车辆装运钢坯支数为${record.amountTotal}` : '',
            confirm: sendCar.bind(null, record),
          },
        },
      ];
    }
    return actions.concat([
      {
        label: '热装',
        color: 'error',
        // disabled: !!record.outTime,
        onClick: () => {
          openRodLineModal(true, {
            info: record,
            machineConfig: machineConfigs()[MachineConfigType.RODLINE],
            title: [[queryParam.value.ccmNo + '#机热装'], ['车牌号：', record.licensePlate], ['目的地：', record.destination]],
            isUpdate: true,
          });
        },
      },
      {
        label: '堆垛装车',
        // disabled: !!record.outTime,
        color: 'warning',
        onClick: () => {
          openStackingEntruckingModal(true, {
            info: record,
            machineConfig: machineConfigs()[MachineConfigType.STACKING],
            destinationList: machineConfigs()[MachineConfigType.RODLINE],
            title: [[queryParam.value.ccmNo + '#机堆垛装车'], ['车牌号：', record.licensePlate], ['目的地：', record.destination]],
            isUpdate: true,
          });
        },
      },

      {
        label: '票据',
        onClick: () => {
          openPrintModal(true, { record, isUpdate: true, type: 'offline' });
        },
        disabled: false,
      },
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        // disabled: record.isUpd,
      },
    ]);
  }

  const openTypeConfigIdModal = ref(false);
  const currentRecord = ref<any>();
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '装运明细',
        onClick: () => {
          openDetailModal(true, { record, isUpdate: true });
        },
        disabled: false,
      },
      {
        label: '打印',
        onClick: () => {
          openPrintModal(true, { record, isUpdate: true });
        },
        disabled: false,
      },
      {
        label: '日志',
        onClick: handleLog.bind(null, record),
        disabled: false,
      },
      {
        label: '修改目的地',
        onClick: () => {
          openTypeConfigIdModal.value = true;
          currentRecord.value = record;
        },
        disabled: false,
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        },
        disabled: false,
      },
    ];
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, formSubmitSuccess);
  }

  // 查看操作日志
  function handleLog(record: Recordable) {
    logRef.value.tableId = record.id;
    logRef.value.showLog(record.id);
  }
  // 删除

  async function handleDelete(record: Recordable) {
    await deleteOne({ id: record.id }, formSubmitSuccess);
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    modelRef.value.edit(record);
    modelRef.value.rowData = record;
  }

  // 获取表格数据
  const getList = (params) => {
    return defHttp.get({
      url: '/storageBill/list',
      params: {
        ...params,
        ccmNo: queryParam.value.ccmNo || '5',
      },
    });
  };
  //注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      title: '',
      api: getList,
      beforeFetch: (params) => {
        return Object.assign(params, {
          ccmNo: Number(queryParam.value.ccmNo),
        });
      },
      afterFetch: (data) => {
        return data.map((item) => {
          return {
            ...item,
            licensePlateOrg: item.licensePlate,
            destinationId: item.typeConfigId === '1024' ? undefined : item.typeConfigId,
            outTimeDate: item.outTime ? dayjs(item.outTime) : '',
          };
        });
      },
      columns,
      canResize: false,
      showActionColumn: false,
      useSearchForm: true,
      showIndexColumn: true,
      indexColumnProps: {
        fixed: 'left',
        width: 220,
        slots: { customRender: 'billXuhao' },
        title: '序号',
      },
      rowClassName: (record: any) => {
        return record.licensePlateStatus === 1 ? 'licensePlate-error-500' : '';
      },
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [
          ['outTime', ['outTime_begin', 'outTime_end'], 'YYYY-MM-DD'],
          ['arrivalTime', ['arrivalTime_begin', 'arrivalTime_end'], 'YYYY-MM-DD'],
        ],
      },
      striped: true,
      actionColumn: {
        width: 340,
        title: '操作',
        fixed: 'right',
      },
      pagination: {
        pageSizeOptions: ['5', '10', '15', '20', '30'],
        defaultPageSize: 5,
      },
      rowSelection: { type: 'checkbox' },
    },
  });

  const [registerTable, { reload, setLoading }, { rowSelection, selectedRowKeys }] = tableContext;
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  // 成功后同时刷新列表和模板
  function formSubmitSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  const changeType = (v) => {
    queryParam.value.positionNum = v == 5 ? '1' : '3';
    reload();
  };

  /**
   * 新增事件
   */
  function handleAdd() {
    if (!queryParam.value.ccmNo) {
      message.error('请选择铸机！');
      return;
    }
    if (!queryParam.value.licensePlate) {
      message.error('请选择车号！');
      return;
    }
    if (!queryParam.value.size) {
      message.error('请选择定尺！');
      return;
    }
    if (!queryParam.value.destination) {
      message.error('请选择目的地！');
      return;
    }
    const destinationInfo = destinationOptions[queryParam.value.ccmNo].find((item) => item.value === queryParam.value.destination);
    defHttp
      .post(
        {
          url: '/storageBill/add',
          params: { ...queryParam.value, destination: destinationInfo?.label, typeConfigId: destinationInfo?.value },
        },
        { joinParamsToUrl: true }
      )
      .then(() => {
        handleSuccess();
        queryParam.value = {
          ccmNo: machine,
          licensePlate: '',
          btype: '0',
          positionNum: Number(machine) === 5 ? '1' : '2',
          size: '',
          destination: '',
        };
      });
  }

  // 修改类型
  function handleBtypeChange(v, record) {
    createConfirm({
      iconType: 'warning',
      title: '确认修改',
      width: '460px',
      content: () => {
        return h('div', { style: { fontSize: '16px' } }, [
          h('span', null, `是否将车牌为`),
          h('span', { style: { fontSize: '18px', color: '#d48806' } }, `${record.licensePlate}`),
          h('span', null, `的`),
          h('span', { style: { fontSize: '18px', color: v === '1' ? '#cd201f' : '#3b5999' } }, `${v === '1' ? ' 热坯 ' : ' 冷坯 '}`),
          h('span', null, `改为`),
          h('span', { style: { fontSize: '18px', color: v === '1' ? '#3b5999' : '#cd201f' } }, `${v === '1' ? ' 冷坯 ' : ' 热坯 '}`),
          h('span', null, `?`),
        ]);
      },
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return edit({ id: record.id, btype: v }).then(() => {
          handleSuccess();
        });
      },
      onCancel: () => {
        record.btype = v === '1' ? '0' : '1';
      },
    });
  }

  // 修改目的地
  function handleDestinationIdChange(v, record) {
    if (!v) return;
    const destinationInfo = destinationOptions[record.ccmNo].find((item) => item.value === v);
    createConfirm({
      iconType: 'warning',
      title: '确认修改',
      width: '460px',
      content: () => {
        return h('div', { style: { fontSize: '16px' } }, [
          h('span', null, `是否修改目的地为：`),
          h('span', { style: { fontSize: '18px', color: '#d48806' } }, ` ${destinationInfo.label} `),
          h('span', null, `?`),
        ]);
      },
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        const fetchFn = record.typeConfigId === '1024' ? edit : destinationSwitch;
        return fetchFn({
          ...record,
          typeConfigId: v,
          destination: destinationInfo.label,
        }).then(() => {
          handleSuccess();
          openTypeConfigIdModal.value = false;
        });
      },
      onCancel: () => {
        record.destinationId = record.typeConfigId === '1024' ? undefined : v;
      },
    });
  }

  // 修改发车时间
  const onOkOutTime = (v, record) => {
    console.log(v, record);
    createConfirm({
      iconType: 'warning',
      title: '确认修改',
      width: '460px',
      content: () => {
        return h('div', { style: { fontSize: '16px' } }, [
          h('span', null, `是否将发车时间修改为`),
          h('span', { style: { fontSize: '18px', color: '#d48806' } }, `${v.format('YYYY-MM-DD HH:mm:ss')}`),
          h('span', null, `?`),
        ]);
      },
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return edit({ id: record.id, btype: record.btype, licensePlate: record.licensePlate, outTime: v.format('YYYY-MM-DD HH:mm:ss') }).then(() => {
          handleSuccess();
        });
      },
      onCancel: () => {
        record.outTimeDate = dayjs(record.outTime);
      },
    });
  };

  // 修改车号
  function handleLicensePlateChange(v, record) {
    if (!v) return;
    createConfirm({
      iconType: 'warning',
      title: '确认修改',
      width: '460px',
      content: () => {
        return h('div', { style: { fontSize: '16px' } }, [
          h('span', null, `是否修改车辆为：`),
          h('span', { style: { fontSize: '18px', color: '#d48806' } }, ` ${v} `),
          h('span', null, `?`),
        ]);
      },
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return edit({
          id: record.id,
          btype: record.btype,
          licensePlate: record.licensePlate,
          licensePlateStatus: 0,
        }).then(() => {
          handleSuccess();
        });
      },
      onCancel: () => {
        record.licensePlate = record.licensePlateOrg;
      },
    });
  }

  onMounted(() => {
    initDictConfig();
    // initWebSocket();
  });
</script>

<style scoped lang="less">
  .shipping-bill-container {
    padding: 0 10px;
  }
  .disabled {
    color: rgb(97, 98, 99);
    pointer-events: none;
    cursor: not-allowed;
  }
  .default {
    cursor: pointer;
    color: #1890ff;
  }
  .show-error {
    font-size: 12px;
    color: #f5222d;
  }
  .hidden-error {
    display: none;
  }
  :deep(.ant-table-thead) {
    .anticon-form {
      display: none;
    }
  }
  :deep(.ant-row) {
    margin: 3px 0 !important;
    width: 100%;
  }

  :deep(.jeecg-basic-table-form-container) {
    padding: 10px 0;
  }
  // 假禁点灰色按钮
  .disabled-btn {
    background: #f5f5f5 !important;
    border-color: #d9d9d9 !important;
    color: rgba(0, 0, 0, 0.25) !important;
  }
  // 根据炉号末尾数字判断颜色
  :deep(.ant-table-tbody) {
    .highlight-row-odd {
      background-color: #99beff;
      .ant-table-cell-fix-left,
      .ant-table-cell-fix-right {
        background-color: #99beff;
      }
    }
    .highlight-row-even {
      background-color: #99ddff;
      .ant-table-cell-fix-left,
      .ant-table-cell-fix-right {
        background-color: #99ddff;
      }
    }

    .jeecg-basic-table-action {
      justify-content: flex-end;
    }

    .ant-switch {
      background-color: #3b5999;
    }

    .ant-switch.ant-switch-checked {
      background-color: #cd201f;
    }

    .ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector {
      background-color: #e7e7e7;
    }
  }
  .form-row {
    .ant-form-item {
      margin-bottom: 20px;
    }
  }

  .shipping-bill-talbe {
    :deep(.licensePlate-error-500) {
      position: relative;

      td:first-child {
        position: relative;
        z-index: 8;
        // border-bottom: 1px solid var(--vxe-danger-color, #f56c6c) !important;

        &::after {
          content: '';
          position: absolute;
          top: 0;
          inset-inline-start: 0;
          width: 100%;
          height: 100%;
          box-shadow: inset 5px 0 0 var(--vxe-danger-color, #f56c6c);
        }
      }

      td:last-child {
        z-index: 8;
        // border-bottom: 1px solid var(--vxe-danger-color, #f56c6c) !important;
      }

      &::after {
        position: absolute;
        top: 0;
        inset-inline-start: 0;
        width: 100%;
        height: 100%;
        // animation-name: errNoticeAnimation;
        // animation-duration: 1.2s;
        // animation-iteration-count: infinite;
        // animation-timing-function: ease-in-out;
        content: '';
        z-index: -1;
        // box-shadow: inset 5px -1px 0 var(--vxe-danger-color, #f56c6c);
      }
    }
  }

  @keyframes errNoticeAnimation {
    0% {
      opacity: 1;
    }

    100% {
      opacity: 0;
    }
  }
</style>
