<template>
  <t-table
    size="small"
    row-key="id"
    :columns="columns"
    :data="tableData"
    bordered
    class="mt-10px"
  >
    <template #deviceStatus="{ row }">
      {{ RUNNING_STATUS[row.deviceStatus] }}
    </template>
    <template #status="{ row }">
      {{ DEVICE_SIGN_STATUS[row.status] }}
    </template>
    <template #transferMode="{ row }">
      {{ DEVICE_TRANSPORT_METHOD[row.transferMode] }}
    </template>
    <template #operate="{ row }">
      <div class="table-operations" @click.stop>
        <t-link
          theme="primary"
          :disabled="row.haveSign || ['TRANSFER', 'IN'].includes(row.status)"
          hover="color"
          @click="enter(row)"
          >入库</t-link
        >
        <t-link
          theme="primary"
          :disabled="row.haveSign || ['TRANSFER', 'IN'].includes(row.status)"
          hover="color"
          @click="middle(row)"
          >中转</t-link
        >
        <t-link
          theme="primary"
          :disabled="row.haveSign || ['USING'].includes(row.status)"
          hover="color"
          @click="edit(row)"
          >编辑</t-link
        >
      </div>
    </template>
  </t-table>
  <my-dialog
    :visible="showEnterDialog"
    :header="`入库`"
    :width="400"
    :closeOnOverlayClick="false"
    attach="body"
    @close="showEnterDialog = false"
    @confirm="enterConfirm"
  >
    <SearchForm
      :params="enterParams"
      :fields="enterFields"
      :rules="enterRules"
      noBorder
      ref="enterForm"
    ></SearchForm>
  </my-dialog>

  <my-dialog
    :visible="showMiddleDialog"
    :header="`中转`"
    :width="400"
    :closeOnOverlayClick="false"
    attach="body"
    @close="showMiddleDialog = false"
    @confirm="middleConfirm"
  >
    <SearchForm
      :params="middleParams"
      :fields="middleFields"
      :rules="middleRules"
      noBorder
      ref="middleForm"
    ></SearchForm>
  </my-dialog>

  <my-dialog
    :visible="showEditDialog"
    :header="`编辑`"
    :width="400"
    :closeOnOverlayClick="false"
    attach="body"
    @close="showEditDialog = false"
    @confirm="editConfirm"
  >
    <SearchForm
      :params="editParams"
      :fields="editFields"
      :rules="editRules"
      noBorder
      ref="editForm"
    ></SearchForm>
  </my-dialog>
</template>
<script name="DeviceManageNewTab2" setup>
import { ref, computed, onMounted, watch } from 'vue';
import {
  RUNNING_STATUS,
  DEVICE_SIGN_STATUS,
  DEVICE_TRANSPORT_METHOD,
} from '@/config/constants';
import { dictToOptionList } from '@/utils/tool';
import { cloneDeep, omit } from 'lodash-es';
import {
  deviceGotoListApi,
  deviceGotoInHandleApi,
  deviceGotoMiddleHandleApi,
  deviceGotoEditHandleApi,
} from '@/api/sop';
import { useRequest } from 'vue-request';
import { MessagePlugin } from 'tdesign-vue-next';

const props = defineProps({
  sop: {
    type: Object,
    default() {
      return {};
    },
  },
});
const { data: tableData, run, loading } = useRequest(deviceGotoListApi);
const fetchData = () => {
  run({ crmNo: props.sop.crmNo });
};
onMounted(() => {
  fetchData();
});

const curRow = ref(null);

/**入库弹框 */
const enterForm = ref();
const showEnterDialog = ref(false);
const initEnterParams = { inMode: 'MAIL', expressNo: '', remark: '' };
const enterParams = ref(cloneDeep(initEnterParams));
const enterFields = computed(() => {
  return [
    {
      prop: 'inMode',
      label: '入库方式：',
      type: 'select',
      labelWidth: 110,
      colSpan: 24,
      options: [
        { value: 'MAIL', label: '邮寄' },
        { value: 'OTHER', label: '其它' },
      ],
    },
    enterParams.value.inMode === 'MAIL'
      ? {
          prop: 'expressNo',
          label: '快递单号：',
          labelWidth: 110,
          colSpan: 24,
        }
      : null,
    {
      prop: 'remark',
      label: '备注：',
      labelWidth: 110,
      colSpan: 24,
    },
  ];
});
const enterRules = computed(() => {
  return {
    inMode: [{ required: true, message: '请选择入库方式' }],
    remark: [
      { required: enterParams.value.inMode === 'OTHER', message: '请填写备注' },
    ],
    expressNo: [
      {
        required: enterParams.value.inMode === 'MAIL',
        message: '请填写快递单号',
      },
    ],
  };
});
const enter = (row) => {
  curRow.value = row;
  enterParams.value = cloneDeep(initEnterParams);
  showEnterDialog.value = true;
};
const enterConfirm = async () => {
  const formRef = enterForm.value.formRef;
  const valid = await formRef?.validate();
  if (valid !== true) return;
  deviceGotoInHandleApi(
    omit(
      {
        id: curRow.value.id,
        inMode: enterParams.value.inMode,
        expressNo: enterParams.value.expressNo,
        remark: enterParams.value.remark,
      },
      enterParams.value.inMode === 'MAIL' ? '' : 'expressNo'
    )
  ).then(() => {
    MessagePlugin.success('操作成功');
    fetchData();
    showEnterDialog.value = false;
  });
};
/***********/

/**中转弹框 */
const middleForm = ref();
const showMiddleDialog = ref(false);
const initMiddleParams = {
  transferMode: 'MAIL',
  expressNo: '',
  remark: '',
  receiveCrmNo: '',
};
const middleParams = ref(cloneDeep(initMiddleParams));
const middleFields = computed(() => {
  return [
    {
      prop: 'transferMode',
      label: '中转方式：',
      type: 'select',
      labelWidth: 110,
      colSpan: 24,
      options: [
        { value: 'MAIL', label: '邮寄' },
        { value: 'OTHER', label: '其它' },
      ],
    },
    middleParams.value.transferMode === 'MAIL'
      ? {
          prop: 'expressNo',
          label: '快递单号：',
          labelWidth: 110,
          colSpan: 24,
        }
      : null,
    {
      prop: 'remark',
      label: '备注：',
      labelWidth: 110,
      colSpan: 24,
    },
    {
      prop: 'receiveCrmNo',
      label: '接收方单号：',
      labelWidth: 110,
      colSpan: 24,
    },
  ];
});
const middleRules = computed(() => {
  let obj = {
    transferMode: [{ required: true, message: '请选择中转方式' }],
    receiveCrmNo: [{ required: true, message: '请填写接收方单号' }],
  };
  if (middleParams.value.transferMode === 'MAIL') {
    obj.expressNo = [{ required: true, message: '请填写快递单号' }];
  } else {
    obj.remark = [{ required: true, message: '请填写备注' }];
  }
  return obj;
});
const middle = (row) => {
  curRow.value = row;
  middleParams.value = cloneDeep(initMiddleParams);
  showMiddleDialog.value = true;
};
const middleConfirm = async () => {
  const formRef = middleForm.value.formRef;
  const valid = await formRef?.validate();
  if (valid !== true) return;
  deviceGotoMiddleHandleApi(
    omit(
      {
        id: curRow.value.id,
        transferMode: middleParams.value.transferMode,
        expressNo: middleParams.value.expressNo,
        remark: middleParams.value.remark,
        receiveCrmNo: middleParams.value.receiveCrmNo,
      },
      middleParams.value.transferMode === 'OTHER' ? 'expressNo' : ''
    )
  ).then(() => {
    MessagePlugin.success('操作成功');
    fetchData();
    showMiddleDialog.value = false;
  });
};

/***********/

/**编辑弹框 */
const editForm = ref();
const showEditDialog = ref(false);
const initEditParams = {
  transferStatus: '',
  transferMode: '',
  expressNo: '',
  receiveCrmNo: '',
  remark: '',
};
const editParams = ref(cloneDeep(initEditParams));
const editFields = computed(() => {
  return [
    {
      prop: 'transferStatus',
      label: '使用状态：',
      type: 'select',
      labelWidth: 110,
      colSpan: 24,
      options: [
        { value: 'TRANSFER', label: '中转' },
        { value: 'IN', label: '入库' },
      ],
    },
    {
      prop: 'transferMode',
      label: '中转方式：',
      type: 'select',
      labelWidth: 110,
      colSpan: 24,
      options: [
        { value: 'MAIL', label: '邮寄' },
        { value: 'OTHER', label: '其它' },
      ],
    },
    editParams.value.transferMode === 'MAIL'
      ? {
          prop: 'expressNo',
          label: '快递单号：',
          labelWidth: 110,
          colSpan: 24,
        }
      : null,
    editParams.value.transferStatus === 'TRANSFER'
      ? {
          prop: 'receiveCrmNo',
          label: '接收方单号：',
          labelWidth: 110,
          colSpan: 24,
        }
      : null,
    editParams.value.transferStatus === 'TRANSFER' ||
    editParams.value.transferMode === 'OTHER'
      ? {
          prop: 'remark',
          label: '备注：',
          labelWidth: 110,
          colSpan: 24,
        }
      : null,
  ];
});
const editRules = computed(() => {
  return {
    transferStatus: [{ required: true, message: '请选择使用状态' }],
    transferMode: [{ required: true, message: '请选择中转方式' }],
    expressNo: [{ required: true, message: '请填写快递单号' }],
    receiveCrmNo: [{ required: true, message: '请填写接收方单号' }],
    remark: [
      {
        required: editParams.value.transferMode === 'OTHER',
        message: '请填写备注',
      },
    ],
  };
});
const edit = (row) => {
  curRow.value = row;
  editParams.value = {
    transferStatus: row.status,
    transferMode: row.transferMode,
    expressNo: row.expressNo,
    receiveCrmNo: row.receiveCrmNo,
    remark: row.remark,
  };
  showEditDialog.value = true;
};
const editConfirm = async () => {
  const formRef = editForm.value.formRef;
  const valid = await formRef?.validate();
  if (valid !== true) return;
  deviceGotoEditHandleApi(
    editParams.value.transferStatus === 'TRANSFER' &&
      editParams.value.transferMode === 'MAIL'
      ? {
          id: curRow.value.id,
          transferStatus: editParams.value.transferStatus,
          transferMode: editParams.value.transferMode,
          expressNo: editParams.value.expressNo,
          remark: editParams.value.remark,
          receiveCrmNo: editParams.value.receiveCrmNo,
        }
      : editParams.value.transferStatus === 'TRANSFER' &&
        editParams.value.transferMode === 'OTHER'
      ? {
          id: curRow.value.id,
          transferStatus: editParams.value.transferStatus,
          transferMode: editParams.value.transferMode,
          remark: editParams.value.remark,
          receiveCrmNo: editParams.value.receiveCrmNo,
        }
      : editParams.value.transferStatus === 'IN' &&
        editParams.value.transferMode === 'MAIL'
      ? {
          id: curRow.value.id,
          transferStatus: editParams.value.transferStatus,
          transferMode: editParams.value.transferMode,
          expressNo: editParams.value.expressNo,
        }
      : {
          id: curRow.value.id,
          transferStatus: editParams.value.transferStatus,
          transferMode: editParams.value.transferMode,
          remark: editParams.value.remark,
        }
  ).then(() => {
    MessagePlugin.success('操作成功');
    fetchData();
    showEditDialog.value = false;
  });
};
/***********/

const columns = [
  {
    colKey: 'serial-number',
    title: '序号',
    width: 48,
  },
  { colKey: 'serialNo', title: '设备序列号' },
  { colKey: 'model', title: '设备型号' },
  { colKey: 'deviceStatus', title: '状态', cell: 'deviceStatus' },
  { colKey: 'supplierName', title: '设备归属' },
  { colKey: 'transferMode', title: '运输方式', cell: 'transferMode' },
  { colKey: 'status', title: '使用状态', cell: 'status' },
  { colKey: 'receiveCrmNo', title: '接收方单号' },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 180,
  },
];
const emit = defineEmits(['getTableData']);
watch(tableData, (val) => {
  emit('getTableData', val);
});
</script>
<style lang="less" scoped></style>
