<template>
  <view class="content">
    <view class="card" style="padding-left: 20px;">
      <u-form labelPosition="left" :model="form" :rules="rules" ref="formRef" labelWidth="140px">
        <u-form-item label="车牌类型" prop="LICENCE_TYPE" borderBottom required
                     @click="fnSingleChoiceClick('LICENCE_TYPE')">
          <u-input v-model="form.LICENCE_TYPE_NAME" border="none" readonly input-align="right"/>
          <u-icon name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item label="车牌号" prop="LICENCE_NO" borderBottom required>
          <u-input v-model="form.LICENCE_NO" border="none" :readonly="!!VEHICLE_ID" input-align="right"/>
        </u-form-item>
        <u-form-item label="车辆类型" prop="VEHICLE_TYPE" borderBottom required
                     @click="fnSingleChoiceClick('VEHICLE_TYPE')">
          <u-input v-model="form.VEHICLE_TYPE_NAME" border="none" readonly input-align="right"/>
          <u-icon name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item label="范围" prop="portId" borderBottom required
                     @click="fnSingleChoiceClick('portId')">
          <u-input v-model="form.portName" border="none" readonly input-align="right"/>
          <u-icon name="arrow-right"></u-icon>
        </u-form-item>
        <u-cell title="车辆所属部门" :value="$store.getters.getUserInfo.DEPARTMENT_NAME"></u-cell>
        <u-cell title="负责人" :value="$store.getters.getUserInfo.NAME"></u-cell>

        <app-time v-model="form.VISIT_START_TIME" prop="VISIT_START_TIME" label="有效期开始"/>
        <app-time v-model="form.VISIT_END_TIME" prop="VISIT_END_TIME" label="有效期结束"/>
        <u-form-item label="审核公司" prop="corpInfo" borderBottom required
                     @click="fnSingleChoiceClick('corpInfoList')">
          <u-input v-model="form.corpInfoName" border="none" readonly input-align="right"/>
          <u-icon name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item label="审批人" prop="QY_AUDITOR" borderBottom required
                     @click="fnSingleChoiceClick('QY_AUDITOR')">
          <u-input v-model="form.QY_AUDITOR_NAME" border="none" readonly input-align="right"/>
          <u-icon name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item label="行驶证照片" prop="drivingImgFiles" borderBottom required labelPosition="top"
                     labelWidth="auto">
          <u-upload class="mt-10"
                    multiple
                    :fileList="form.drivingImgFiles"
                    :maxCount="2"
                    :preview-full-image="true"
                    @afterRead="fnAfterRead($event, 'drivingImgFiles')"
                    @delete="fnDeletePic($event, 'drivingImgFiles')"
          ></u-upload>
        </u-form-item>
        <u-form-item label="车辆照片" prop="vehicleImgFiles" borderBottom required labelPosition="top"
                     labelWidth="auto">
          <u-upload class="mt-10"
                    multiple
                    :fileList="form.vehicleImgFiles"
                    :maxCount="10"
                    :preview-full-image="true"
                    @afterRead="fnAfterRead($event, 'vehicleImgFiles')"
                    @delete="fnDeletePic($event, 'vehicleImgFiles')"
          ></u-upload>
        </u-form-item>
      </u-form>
      <view class="mt-10">
        <u-button type="primary" text="提交" @click="$u.debounce(fnSubmit, 1000, true)"/>
      </view>
    </view>
    <u-picker :show="picker.show" :columns="picker.columns" :keyName="picker.key" :key="picker.type"
              :defaultIndex="picker.defaultIndex" @confirm="fnSingleChoiceConfirm" @cancel="fnSingleChoiceCancel" />
  </view>
</template>

<script>
import AppTime from "@/components/time/index.vue";
import AppDepartment from "@/components/department/index.vue";
import AppPersonnel from "@/components/personnel/index.vue";
import {
  goCheckLicenceNo, getVehiclemessageView, setVehiclemessageSave, getCorpInfoList,
  setVehiclemessageUpdate, getAuditUserList, uploadSmd, getVehicleTypeList
} from "@/api";
export default {
  components: {
    AppTime,
    AppDepartment,
    AppPersonnel,
  },
  data() {
    return {
      VEHICLE_ID: '',
      VEHICLE_LICENSE_PLATE_TYPE_LIST: [
        {id: '0', name: "白牌"},
        {id: '1', name: "蓝牌"},
        {id: '2', name: "黄牌"},
        {id: '3', name: "绿牌"},
        {id: '4', name: "黑牌"},
      ],
      VEHICLE_PORT_LIST: [
        {id: "0", name: "全部"},
        {id: "1", name: "东港区"},
        {id: "2", name: "西港区"},
      ],
      VEHICLE_TYPE_LIST: [],
      form: {
        LICENCE_TYPE: '',
        LICENCE_TYPE_NAME: '',
        LICENCE_NO: '',
        VEHICLE_TYPE: '',
        VEHICLE_TYPE_NAME: '',
        DEPARTMENT_ID: '',
        DEPARTMENT_NAME: '',
        USER_ID: '',
        USER_NAME: '',
        VISIT_START_TIME: '',
        VISIT_END_TIME: '',
        AUDITOR_DEPARTMENT_ID: '',
        AUDITOR_DEPARTMENT_NAME: '',
        portId: '',
        QY_AUDITOR:'',
        QY_AUDITOR_NAME:'',
        drivingImgFiles: [],
        vehicleImgFiles: [],
        deleteFileIds: [],
      },
      rules: {
        LICENCE_TYPE: [{type: 'string', required: true, message: '请选择车牌类型', trigger: ['blur', 'change']}],
        LICENCE_NO: [{type: 'string', required: true, message: '请输入车牌号', trigger: ['blur', 'change']}],
        VEHICLE_TYPE: [{type: 'string', required: true, message: '请选择车辆类型', trigger: ['blur', 'change']}],
        DEPARTMENT_ID: [{type: 'string', required: true, message: '请选择车辆所属部门', trigger: ['blur', 'change']}],
        USER_ID: [{type: 'string', required: true, message: '请选择负责人', trigger: ['blur', 'change']}],
        VISIT_START_TIME: [{type: 'string', required: true, message: '请选择有效期开始', trigger: ['blur', 'change']}],
        VISIT_END_TIME: [{type: 'string', required: true, message: '请选择有效期结束', trigger: ['blur', 'change']}],
        AUDITOR_DEPARTMENT_ID: [{type: 'string', required: true, message: '请选择审核部门', trigger: ['blur', 'change']}],
        vehicleImgFiles: [{type: 'array', required: true, message: '请上传车辆照片', trigger: ['blur', 'change']}],
        drivingImgFiles: [{type: 'array', required: true, message: '请上传行驶证照片', trigger: ['blur', 'change']}]
      },
      picker: {
        show: false,
        columns: [],
        key: 'name',
        type: 'picker',
        defaultIndex: []
      },
      corpInfoList: [],
    }
  },
  onLoad(event) {
    this.VEHICLE_ID = event.VEHICLE_ID
    if (event.VEHICLE_ID) {
      uni.setNavigationBarTitle({
        title: "重新申请",
      });
      this.getData();
    }
    this.getCorpInfoList()
    this.getVehicleTypes();
  },
  computed: {
    userInfo() {
      return this.$store.getters.getUserInfo
    }
  },
  methods: {
    fnSingleChoiceClick(event) {
      this.picker.type = event
      if (event === 'LICENCE_TYPE') {
        this.picker.columns = [this.VEHICLE_LICENSE_PLATE_TYPE_LIST]
      }
      if (event === 'VEHICLE_TYPE') {
        this.picker.columns = [this.VEHICLE_TYPE_LIST]
      }
      if (event === 'portId') {
        this.picker.columns = [this.VEHICLE_PORT_LIST]
      }
      if (event === 'corpInfoList') {
        this.picker.columns = [this.corpInfoList]
        this.form.QY_AUDITOR = ''
        this.form.QY_AUDITOR_NAME = ''
      }
      if (event === 'QY_AUDITOR') {
        this.form.QY_AUDITOR = ''
        this.form.QY_AUDITOR_NAME = ''
        this.picker.columns = [this.userList]
      }

      this.picker.show = true
    },
    fnSingleChoiceConfirm(event) {
      if (this.picker.type === 'LICENCE_TYPE') {
        this.form.LICENCE_TYPE = event.value[0].id
        this.form.LICENCE_TYPE_NAME = event.value[0].name
      }
      if (this.picker.type === 'VEHICLE_TYPE') {
        this.form.VEHICLE_TYPE = event.value[0].id
        this.form.VEHICLE_TYPE_NAME = event.value[0].name
      }
      if (this.picker.type === 'portId') {
        this.form.portId = event.value[0].id
        this.form.portName = event.value[0].name
      }
      console.info(' this.picker.type')
      console.info( this.picker.type)
      if (this.picker.type === 'corpInfoList') {
        this.form.corpInfoId = event.value[0].corpinfo_ID
        this.form.corpInfoName = event.value[0].name
        this.getUserList(event.value[0].corpinfo_ID)
      }
      if (this.picker.type === 'QY_AUDITOR') {
        this.form.QY_AUDITOR = event.value[0].userId
        this.form.QY_AUDITOR_NAME = event.value[0].name
      }
      this.fnSingleChoiceCancel()
    },
    fnSingleChoiceCancel() {
      this.picker.show = false
    },
    async fnSubmit() {
      try {
        await this.$refs.formRef.validate()
        const checkRes = await goCheckLicenceNo({
          LICENCE_NO: this.form.LICENCE_NO,
          licenceType: this.form.LICENCE_TYPE,
          VEHICLE_ID :  this.VEHICLE_ID || ''
        });
        if (checkRes.exists === '1') {
          uni.$u.toast('车牌号已存在')
          return
        }
        const vehicleImgs = [];
        const drivingImgs = [];
        for (let i = 0; i < this.form.vehicleImgFiles.length; i++) {
          if (!this.form.vehicleImgFiles[i].imgfilesId) {
            const { imgUrl } = await uploadSmd({
              filePath: this.form.vehicleImgFiles[i].url,
              name: "file",
            });
            vehicleImgs.push(imgUrl);
          }
        }
        for (let i = 0; i < this.form.drivingImgFiles.length; i++) {
          if (!this.form.drivingImgFiles[i].imgfilesId) {
            const { imgUrl } = await uploadSmd({
              filePath: this.form.drivingImgFiles[i].url,
              name: "file",
            });
            drivingImgs.push(imgUrl);
          }
        }
        const params = {
          ...this.form,
          DEPARTMENT_ID: this.userInfo.DEPARTMENT_ID,
          USER_ID: this.userInfo.USER_ID,
          VEHICLE_DEPARTMENT_ID: this.userInfo.DEPARTMENT_ID,
          VEHICLE_DEPARTMENT_NAME: this.userInfo.DEPARTMENT_NAME,
          carForm:'2',
          vehicleImgs: JSON.stringify(vehicleImgs),
          drivingImgs: JSON.stringify(drivingImgs),
          deleteFileIds: JSON.stringify(this.form.deleteFileIds),
          vehicleImgFiles: null,
          drivingImgFiles: null,
          OLD_LICENCE_NO: this.form.LICENCE_NO,
          VEHICLE_BELONG_TYPE: "0"
        }
        this.VEHICLE_ID ? await setVehiclemessageUpdate(params) : await setVehiclemessageSave(params)
        uni.navigateBack(); // 返回上一页
      } catch(e) {
        uni.$u.toast(e?.msg || '请补全必填项')
      }
    },
    async getCorpInfoList() {
      const resData = await getCorpInfoList({ TYPES: [0, 2] })
      this.corpInfoList = resData.list.corpInfoDos
    },
    async getUserList(corpinfoId) {
      const resData = await getAuditUserList(
          {corpinfoId: corpinfoId}
      );
      this.userList = resData.data;
    },
    async getData() {
      const resData = await getVehiclemessageView({VEHICLE_ID: this.$route.query.VEHICLE_ID});
      this.form = resData.pd;
      const matchedItem = this.VEHICLE_LICENSE_PLATE_TYPE_LIST.find(item => item.id === resData.pd.LICENCE_TYPE.toString());
      if (matchedItem) {
        this.form.LICENCE_TYPE_NAME = matchedItem.name;
        this.form.LICENCE_TYPE = resData.pd.LICENCE_TYPE.toString();
      }
      const vehicleType = this.VEHICLE_TYPE_LIST.find(item => item.id === resData.pd.VEHICLE_TYPE.toString());
      if (vehicleType) {
        this.form.VEHICLE_TYPE_NAME = vehicleType.name;
        this.form.VEHICLE_TYPE = resData.pd.VEHICLE_TYPE.toString();
      }
      const vehiclePort = this.VEHICLE_PORT_LIST.find(item => item.id === resData.pd.portId.toString());
      if (vehiclePort) {
        this.form.portName = vehiclePort.name;
        this.form.portId = resData.pd.portId.toString();
      }
      this.form.corpInfoName = this.form.QY_AUDITOR_CORP_NAME
      this.form.corpInfoId = this.form.QY_AUDITOR_CORP_ID
      for (let i = 0; i < resData.pd.drivingImgs.length; i++) {
        if (!Array.isArray(this.form.drivingImgFiles)) {
          this.$set(this.form, "drivingImgFiles", []);
        }
        this.form.drivingImgFiles.push({
          url: this.$filePath + resData.pd.drivingImgs[i].filepath,
          ...resData.pd.drivingImgs[i],
        });
      }
      for (let i = 0; i < resData.pd.vehicleImgs.length; i++) {
        if (!Array.isArray(this.form.vehicleImgFiles)) {
          this.$set(this.form, "vehicleImgFiles", []);
        }
        this.form.vehicleImgFiles.push({
          url: this.$filePath + resData.pd.vehicleImgs[i].filepath,
          ...resData.pd.vehicleImgs[i],
        });
      }
    },
    fnAfterRead(event, key) {
      // 统一处理为数组格式 (兼容单文件/多文件上传)
      const fileList = Array.isArray(event.file) ? event.file : [event.file];
      // 确保目标字段是响应式数组
      if (!Array.isArray(this.form[key])) {
        this.$set(this.form, key, []);
      }
      // 批量创建新对象并追加 (浅拷贝)
      const newFiles = fileList.map(file => ({ ...file }));
      this.form[key] = [...this.form[key], ...newFiles];
    },
    fnDeletePic(event, key) {
      uni.showModal({
        title: '提示',
        content: '确定删除该图片吗？',
        success: (res) => {
          if (res.confirm) {
            if (event?.file?.imgfilesId) {
              this.form.deleteFileIds = this.form.deleteFileIds == null ? [] : this.form.deleteFileIds
              this.form.deleteFileIds.push(event.file.imgfilesId);
            }
            this.form[key].splice(event.index, 1)
          }
        }
      })
    },
    async getVehicleTypes() {
      const { list } = await getVehicleTypeList();
      const TYPE_LIST = [];
      for (let i = 0; i < list.length; i++){
        TYPE_LIST.push({id: list[i].BIANMA, name: list[i].NAME})
      }
      this.VEHICLE_TYPE_LIST = TYPE_LIST;
    },
  },
}
</script>

<style scoped lang="scss">

</style>
