<template>
  <my-dialog
    :visible="visible"
    :header="title"
    :width="700"
    attach="body"
    :closeOnOverlayClick="false"
    @close="emit('update:visible', false)"
    @opened="dialogOpened"
  >
    <t-form
      ref="formRef"
      :data="formData"
      :rules="rules"
      :labelWidth="120"
      colon
    >
      <t-form-item label="设备序列号" name="serialNo">
        <t-select
          v-model="formData.serialNo"
          :options="deviceOptions"
          @change="deviceChange"
          filterable
          disabled
        >
        </t-select>
      </t-form-item>
      <t-form-item v-if="!isOutType" label="运行状态" name="deviceStatus">
        <t-select
          v-model="formData.deviceStatus"
          :options="dictToOptionList(RUNNING_STATUS)"
        ></t-select>
      </t-form-item>
      <t-form-item v-if="!isOutType" label="总扫描量" name="scanCount">
        <t-input-number
          v-model="formData.scanCount"
          theme="column"
          :decimalPlaces="1"
          :max="100000000"
          :min="0"
          style="width: 120px"
        ></t-input-number>
      </t-form-item>
      <t-form-item
        v-if="isOutType"
        label="发往地"
        name="addressArr"
        required-mark
      >
        <select-area
          v-model="formData.addressArr"
          value-type="full"
        ></select-area>
      </t-form-item>

      <t-form-item label="快递单拍照" name="basePhotoPath">
        <my-upload
          v-model="files"
          :imgLength="1"
          @change="imgChange"
        ></my-upload>
      </t-form-item>
      <t-form-item label="快递单号" name="expressNo">
        <t-input v-model="formData.expressNo" />
      </t-form-item>
    </t-form>
    <template #foot>
      <t-button theme="default" @click="emit('update:visible', false)"
        >取消</t-button
      >
      <t-button theme="primary" @click="save">保存</t-button>
    </template>
  </my-dialog>
</template>
<script setup name="EditColumnDialog">
import { ref, computed, reactive, watch } from 'vue';
import { RUNNING_STATUS } from '@/config/constants';
import { dictToOptionList } from '@/utils/tool';
import { deviceCanOut, deviceCanIn } from '@/api/sop';

const emit = defineEmits(['update:visible', 'success']);
const props = defineProps({
  visible: Boolean,
  curRow: Object,
  isOutType: Boolean,
  tableData: Array,
});

const deviceOptions = ref([]);
const formRef = ref(null);
const files = ref([]);
const formData = reactive({
  key: '',
  deviceNo: '',
  serialNo: '',
  supplierName: '',
  deviceStatus: '',
  scanCount: null,
  location: '',
  address: '',
  addressArr: ['', '', ''],
  basePhotoPath: '',
  expressNo: '',
  deviceBrand: '',
});
watch([() => formData.basePhotoPath, () => formData.expressNo], () => {
  formRef.value.validate();
});
const title = computed(() => {
  return (props.curRow?.key ? '编辑' : '新增') + '记录';
});

const rules = computed(() => {
  return {
    serialNo: [
      {
        required: true,
        message: '不能为空',
        type: 'error',
        trigger: 'change',
      },
    ],
    deviceStatus: [
      {
        required: true,
        message: '不能为空',
        type: 'error',
        trigger: 'change',
      },
    ],
    // scanCount: [
    //   {
    //     required: true,
    //     message: '不能为空',
    //     type: 'error',
    //     trigger: 'change',
    //   },
    // ],
    addressArr: [
      {
        validator: () => {
          if (formData.addressArr.some((item) => !item))
            return { result: false, message: '发往地必选' };

          return { result: true, type: 'success' };
        },
        type: 'error',
        trigger: 'change',
      },
    ],
    basePhotoPath: [
      {
        // required: true,
        validator: () => {
          if (!formData.basePhotoPath && !formData.expressNo)
            return {
              result: false,
              message: '快递单拍照和快递单号至少有一项必填',
            };

          return { result: true, type: 'success' };
        },
        type: 'error',
        trigger: 'change',
      },
    ],
    expressNo: [
      {
        // required: true,
        validator: () => {
          if (!formData.basePhotoPath && !formData.expressNo)
            return {
              result: false,
              message: '快递单拍照和快递单号至少有一项必填',
            };

          return { result: true, type: 'success' };
        },
        type: 'error',
        trigger: 'change',
      },
    ],
  };
});

const getDeviceOptions = async () => {
  const func = props.isOutType ? deviceCanOut : deviceCanIn;
  const res = await func();
  deviceOptions.value = res
    .filter(
      (item) =>
        !(props.tableData || []).find((v) => v.serialNo == item.serialNo)
    )
    .map((item) => ({
      ...item,
      value: item.serialNo,
      label: item.deviceNo + '_' + item.serialNo + '_' + item.deviceBrand,
    }));
};

const imgChange = (fileRes) => {
  formData.basePhotoPath = fileRes.length ? fileRes[0].url : '';
};
const deviceChange = (val, { option }) => {
  formData.supplierName = option.supplierName;
  formData.deviceStatus = option.deviceStatus;
  formData.deviceBrand = option.deviceBrand;
  formData.scanCount = option.scanCount;
  formData.location = option.location;
  // formData.serialNo = option.serialNo;
  formData.deviceNo = option.deviceNo;
  if (!props.isOutType) {
    formData.address = option.supplierName;
  }
};

const dialogOpened = async () => {
  for (let key in formData) {
    formData[key] = props.curRow[key];
  }
  files.value = formData.basePhotoPath ? [{ url: formData.basePhotoPath }] : [];
  await getDeviceOptions();
};

const save = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return;
  let data = {};
  for (let key in formData) {
    data[key] = formData[key];
  }
  if (props.isOutType) data.address = data.addressArr.join('');
  emit('update:visible', false);
  emit('success', data);
};
</script>
