<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" input-align="right"/>
        </u-form-item>
        <u-form-item label="车辆所属类型" prop="VEHICLE_BELONG_TYPE" borderBottom required
                      @click="fnSingleChoiceClick('VEHICLE_BELONG_TYPE')">
          <u-input v-model="form.VEHICLE_BELONG_TYPE_NAME" border="none" readonly input-align="right"/>
          <u-icon name="arrow-right"></u-icon>
        </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="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="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-form-item label="车辆所属部门" prop="DEPARTMENT_NAME" borderBottom required>
          <u-input :value="userInfo.DEPARTMENT_NAME" border="none" readonly input-align="right"/>
        </u-form-item>
        <u-form-item v-if="form.VEHICLE_BELONG_TYPE !== '1'"  label="车辆归属人" prop="USERNAME" borderBottom required>
          <u-input :value="userInfo.USERNAME" border="none" readonly input-align="right"/>
        </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 {
  getAuditUserList,
  getVehiclemessageView,
  getVehicleTypeList,
  goCheckLicenceNo,
  setVehiclemessageSave,
  setVehiclemessageUpdate,
  uploadSmd
} from "@/api";

export default {
  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_TYPE_LIST: [],
      VEHICLE_PORT_LIST: [
        {id: "0", name: "全部"},
        {id: "1", name: "东港区"},
        {id: "2", name: "西港区"},
      ],
      VEHICLE_BELONG_TYPE_LIST: [
        { id: "0", name: "员工车辆" },
        { id: "1", name: "单位车辆" },
      ],
      userList: [],
      form: {
        OLD_LICENCE_NO: '',
        LICENCE_TYPE: '',
        LICENCE_TYPE_NAME: '',
        LICENCE_NO: '',
        VEHICLE_TYPE: '',
        VEHICLE_TYPE_NAME: '',
        QY_AUDITOR: '',
        QY_AUDITOR_NAME: '',
        portId: '',
        portName: '',
        drivingImgFiles: [],
        vehicleImgFiles: [],
        deleteFileIds: [],
        VEHICLE_BELONG_TYPE: '',
        VEHICLE_BELONG_TYPE_NAME: '',
      },
      rules: {
        LICENCE_TYPE: [{type: 'string', required: true, message: '请选择车牌类型', trigger: ['blur', 'change']}],
        LICENCE_NO: [
            {type: 'string', required: true, message: '请输入车牌号', trigger: ['blur', 'change']},
          {
            pattern: /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$/,
            message: "请输入正确的车牌号",
            trigger: "blur",
          }],
        VEHICLE_TYPE: [{type: 'string', required: true, message: '请选择车辆类型', trigger: ['blur', 'change']}],
        QY_AUDITOR: [{type: 'string', required: true, message: '请选择审批人', trigger: ['blur', 'change']}],
        portId: [{type: 'string', required: true, message: '请选择范围', trigger: ['blur', 'change']}],
        vehicleImgFiles: [{type: 'array', min: 2, required: true, message: '请上传车辆照片（最少2张）', trigger: ['blur', 'change']}],
        drivingImgFiles: [{type: 'array', min: 2, required: true, message: '请上传行驶证照片正反面照片', trigger: ['blur', 'change']}]
      },
      picker: {
        show: false,
        columns: [],
        key: 'name',
        type: 'picker',
        defaultIndex: []
      },
    }
  },
  onLoad(event) {
    this.getVehicleTypeList();
    this.getUserList();
    this.VEHICLE_ID = event.VEHICLE_ID
    if (event.VEHICLE_ID) {
      uni.setNavigationBarTitle({
        title: "修改",
      });
      this.getData();
    }
  },
  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 === 'QY_AUDITOR') {
        this.picker.columns = [this.userList]
      }
      if (event === 'portId') {
        this.picker.columns = [this.VEHICLE_PORT_LIST]
      }
      if (event === 'VEHICLE_BELONG_TYPE') {
        this.picker.columns = [this.VEHICLE_BELONG_TYPE_LIST]
      }
      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 === 'QY_AUDITOR') {
        this.form.QY_AUDITOR = event.value[0].userId
        this.form.QY_AUDITOR_NAME = event.value[0].name
      }
      if (this.picker.type === 'portId') {
        this.form.portId = event.value[0].id
        this.form.portName = event.value[0].name
      }
      if (this.picker.type === 'VEHICLE_BELONG_TYPE') {
        this.form.VEHICLE_BELONG_TYPE = event.value[0].id
        this.form.VEHICLE_BELONG_TYPE_NAME = event.value[0].name
      }
      this.fnSingleChoiceCancel()
    },
    fnSingleChoiceCancel() {
      this.picker.show = false
    },
    async getVehicleTypeList() {
      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;
    },
    async getData() {
      const resData = await getVehiclemessageView({VEHICLE_ID: this.VEHICLE_ID});
      // 使用 this.$set 确保表单数据的响应式更新
      Object.keys(resData.pd).forEach(key => {
        this.$set(this.form, key, resData.pd[key]);
      });
      // 处理车牌类型
      const matchedItem = this.VEHICLE_LICENSE_PLATE_TYPE_LIST.find(item => item.id === resData.pd.LICENCE_TYPE.toString());
      if (matchedItem) {
        this.$set(this.form, 'LICENCE_TYPE_NAME', matchedItem.name);
        this.$set(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.$set(this.form, 'VEHICLE_TYPE_NAME', vehicleType.name);
        this.$set(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.$set(this.form, 'portName', vehiclePort.name);
        this.$set(this.form, 'portId', resData.pd.portId.toString());
      }

      // 处理车辆所属类型
      const vehicleOwnership = this.VEHICLE_BELONG_TYPE_LIST.find(item => item.id === resData.pd.VEHICLE_BELONG_TYPE.toString());
      if (vehicleOwnership) {
        this.$set(this.form, 'VEHICLE_BELONG_TYPE', vehicleOwnership.id);
        this.$set(this.form, 'VEHICLE_BELONG_TYPE_NAME', vehicleOwnership.name);
      }

      // 处理审批人
      const auditor = this.userList.find(item => item.userId === resData.pd.QY_AUDITOR);
      if (auditor) {
        this.$set(this.form, 'QY_AUDITOR_NAME', auditor.name);
      }

      // 处理行驶证图片
      this.$set(this.form, 'drivingImgFiles', []);
      if (resData.pd.drivingImgs && Array.isArray(resData.pd.drivingImgs)) {
        resData.pd.drivingImgs.forEach((img, index) => {
          this.$set(this.form.drivingImgFiles, index, {
            url: this.$store.state.filePath + img.filepath,
            ...img,
          });
        });
      }

      // 处理车辆图片
      this.$set(this.form, 'vehicleImgFiles', []);
      if (resData.pd.vehicleImgs && Array.isArray(resData.pd.vehicleImgs)) {
        resData.pd.vehicleImgs.forEach((img, index) => {
          this.$set(this.form.vehicleImgFiles, index, {
            url: this.$store.state.filePath + img.filepath,
            ...img,
          });
        });
      }
    },
    async getUserList() {
      const resData = await getAuditUserList({corpinfoId: this.userInfo.CORPINFO_ID});
      this.userList = resData.data;
    },
    async fnSubmit() {
      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);
        }
      }
      this.form.OLD_LICENCE_NO = this.form.LICENCE_NO;
      const params = {
        ...this.form,
        DEPARTMENT_ID: this.userInfo.DEPARTMENT_ID,
        USER_ID: this.form.VEHICLE_BELONG_TYPE === 1 ? '' : this.userInfo.USER_ID,
        USER_NAME: this.form.VEHICLE_BELONG_TYPE === 1 ? '' : this.userInfo.NAME,
        VEHICLE_DEPARTMENT_ID: this.userInfo.DEPARTMENT_ID,
        VEHICLE_DEPARTMENT_NAME: this.userInfo.DEPARTMENT_NAME,
        vehicleImgs: JSON.stringify(vehicleImgs),
        drivingImgs: JSON.stringify(drivingImgs),
        deleteFileIds: JSON.stringify(this.form.deleteFileIds),
        vehicleFiles: null,
        vehicleImgFiles: null,
        drivingImgFiles: null,
      }
      let resData
      if(this.VEHICLE_ID){
        resData = await setVehiclemessageUpdate(params)
      }else{
        resData = await setVehiclemessageSave(params);
      }
      if (resData.code === '500') {
        uni.$u.toast(resData.msg)
        return
      }
      uni.navigateBack(); // 返回上一页
    },
    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)
          }
        }
      })
    },
  },
}
</script>

<style scoped lang="scss">

</style>
