<template>
  <view class="form-container">
    <!-- 表单标题 -->
    <view class="form-title">
      <text class="title-text">用车申请表</text>
      <view class="title-line"></view>
    </view>
    <uni-forms ref="form" :modelValue="form" :rules="rules" label-position="top" label-width="150" class="custom-form">
      <flow-note :taskForm="taskForm"></flow-note>
      <!-- 当前节点 -->
      <uni-forms-item label="当前节点" class="form-item" v-if="taskName">
        <uni-tag :inverted="true" type="primary" :text="taskName"></uni-tag>
      </uni-forms-item>

      <!-- 流程发起人 -->
      <uni-forms-item label="填报人" class="form-item">
        <b style="font-size:30rpx;">{{ applierUserName }}</b>
      </uni-forms-item>

      <!-- 填报日期 -->
      <uni-forms-item label="填报日期" class="form-item">
        <text>{{ form.applyDate }}</text>
      </uni-forms-item>

      <!-- 借款类型 -->
      <uni-forms-item label="申请用途" required class="form-item" name="carUsage">
        <uni-data-checkbox v-model="form.carUsage" :localdata="carUsageOptions" :disabled="taskName != '用车申请'"
          @change="hanldeChangeType"></uni-data-checkbox>
      </uni-forms-item>

      <!-- 选择项目 -->
      <uni-forms-item label="选择项目" required class="form-item" v-if="form.carUsage == 0" name="projectId">
        <u-button type="primary" @click="openProject = true" v-if="taskName == '用车申请'">+ 选择项目</u-button>
        <ProjectPicker :visible.sync="openProject" :selected.sync="selectedProject" @confirm="handleConfirm" />
        <ProjectInfo :project="projectObj"></ProjectInfo>
      </uni-forms-item>

      <!-- 用车事由 -->
      <uni-forms-item label="用车事由" required class="form-item" name="applyReason">
        <uv-textarea v-model="form.applyReason" placeholder="请输入用车事由" :disabled="taskName != '用车申请'"></uv-textarea>
      </uni-forms-item>

      <!-- 用车时间 -->
      <view class="date-range">
        <uni-forms-item label="使用日期" required class="form-item" name="dateRange">
          <uni-datetime-picker v-model="form.dateRange" type="daterange" rangeSeparator="至" :clearIcon="false"
            v-if="taskName == '用车申请'" @change="handleDateRangeChange" />
          <view class="date-display" v-else>
            <uni-icons type="calendar" size="16"></uni-icons>
            <text class="date-text">{{ form.beginDate }}</text>
            <text class="date-separator">至</text>
            <text class="date-text">{{ form.endDate }}</text>
          </view>
        </uni-forms-item>
        <uni-forms-item label="共计" class="form-item">
          <text>{{ form.days + '天' }}</text>
        </uni-forms-item>
      </view>

      <!-- 乘车人数 -->
      <uni-forms-item label="乘车人数" required class="form-item" name="passengers">
        <uni-number-box v-model="form.passengers" :min="1" :disabled="taskName != '用车申请'" />
      </uni-forms-item>

      <view v-if="taskName != '用车申请'">
        <!-- 部门审核意见 -->
        <uni-forms-item label="部门审核意见" required class="form-item" v-if="showFormItem('部门审核')" name="deptComment">
          <uv-textarea v-model="form.deptComment" placeholder="请输入部门审核意见" :disabled="taskName != '部门审核'"></uv-textarea>
          <auditor :name="form.deptUser ? form.deptUser.nickName : ''" :time="form.deptTime"></auditor>
        </uni-forms-item>

        <!-- 分管审核意见 -->
        <uni-forms-item label="分管审核意见" required class="form-item" v-if="showFormItem('分管审核')" name="managerComment">
          <uv-textarea v-model="form.managerComment" placeholder="请输入分管审核意见"
            :disabled="taskName != '分管审核'"></uv-textarea>
          <auditor :name="form.managerUser ? form.managerUser.nickName : ''" :time="form.managerTime"></auditor>
        </uni-forms-item>

        <!-- 党工团审核意见 -->
        <uni-forms-item :label="dgtAdvice" required class="form-item" v-if="showFormItem('党工团审核')" name="unionComment">
          <uv-textarea v-model="form.unionComment" placeholder="请输入审核意见" :disabled="taskName != '党工团审核'"></uv-textarea>
          <auditor :name="form.unionUser ? form.unionUser.nickName : ''" :time="form.unionTime"></auditor>
        </uni-forms-item>

        <!-- 总经理审核意见 -->
        <uni-forms-item label="总经理审核意见" required class="form-item" v-if="showFormItem('总经理审核')" name="gmComment">
          <uv-textarea v-model="form.gmComment" placeholder="请输入总经理审核意见" :disabled="taskName != '总经理审核'"></uv-textarea>
          <auditor :name="form.gmUser ? form.gmUser.nickName : ''" :time="form.gmTime"></auditor>
        </uni-forms-item>

        <!-- 董事长审核意见 -->
        <uni-forms-item label="董事长审核意见" required class="form-item" v-if="showFormItem('董事长审核')" name="dszComment">
          <uv-textarea v-model="form.dszComment" placeholder="请输入董事长审核意见" :disabled="taskName != '董事长审核'"></uv-textarea>
          <auditor :name="form.dszUser ? form.dszUser.nickName : ''" :time="form.dszTime"></auditor>
        </uni-forms-item>
      </view>
      <view v-if="taskName == '' || taskName == '安排用车'">
        <!-- 安排用车意见 -->
        <uni-forms-item label="安排用车意见" required class="form-item" name="dispatchComment">
          <uv-textarea v-model="form.dispatchComment" placeholder="请输入安排用车意见"
            :disabled="taskName != '安排用车'"></uv-textarea>
          <auditor :name="form.dispatchUser ? form.dispatchUser.nickName : ''" :time="form.dispatchTime"></auditor>
        </uni-forms-item>

        <!-- 车牌号选择 -->
        <uni-forms-item label="车牌号" class="form-item" name="cars">
          <view class="car-list">
            <uv-checkbox-group v-model="form.cars" v-if="taskName == '安排用车'">
              <view class="car-row" v-for="(row, index) in Math.ceil(carList.length / 2)" :key="index">
                <view class="car-item" v-for="item in carList.slice(index * 2, (index + 1) * 2)" :key="item.carId"
                  :class="{ 'is-checked': form.cars.includes(item.carId) }">
                  <uv-checkbox :name="item.carId" :disabled="item.status != 1">
                    <view class="car-info">
                      <text class="car-license">{{ item.licensePlate }}</text>
                      <text class="car-model">{{ item.brand || '' }}{{ item.series || '' }}</text>
                    </view>
                  </uv-checkbox>
                </view>
              </view>
            </uv-checkbox-group>
            <view class="car-row" v-for="(row, index) in Math.ceil(carList.length / 2)" :key="index" v-else>
              <view class="car-item" v-for="item in carList.slice(index * 2, (index + 1) * 2)" :key="item.carId"
                :class="{ 'is-checked': form.cars.includes(item.carId) }">
                <text class="car-license">{{ item.licensePlate }}</text>
                <text class="car-model">{{ item.brand || '' }}{{ item.series || '' }}</text>
              </view>
            </view>
          </view>
        </uni-forms-item>

        <!-- 驾驶员选择 -->
        <uni-forms-item label="驾驶员" class="form-item" name="drivers">
          <u-button type="primary" v-if="taskName == '安排用车'" @click="openCar = true">+ 选择人员</u-button>
          <view class="driver-list" v-if="chooseDriver.length > 0">
            <u-tag v-for="(item, index) in chooseDriver" :plain="true" :key="index" :text="item.nickName"
              style="margin: 5px;" />
          </view>
        </uni-forms-item>

        <!-- 返回日期和行驶公里 -->
        <uni-forms-item label="返回日期" required class="form-item" name="returnDate">
          <uni-datetime-picker v-model="form.returnDate" type="datetime" :disabled="taskName != '安排用车'" />
        </uni-forms-item>

        <uni-forms-item label="行驶公里" class="form-item" name="kilometers">
          <uv-input v-model="form.kilometers" placeholder="请输入行驶公里" :disabled="taskName != '安排用车'"
            @input="handleKilometersInput">
            <template v-slot:suffix>
              <text>公里</text>
            </template>
          </uv-input>
        </uni-forms-item>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn" v-if="taskName == '用车申请'">
        <u-button type="primary" @click="submit">提交申请</u-button>
      </view>
      <view v-else>
        <u-button style="margin-bottom:5px;" type="warning" @click="saves" v-if="taskName == '安排用车'">保存</u-button>
        <u-button type="primary" @click="completeApply"
          :disabled="taskName == '安排用车' && !form.returnDate" v-if="taskName">完成审批</u-button>
      </view>
    </uni-forms>

    <!-- 选择人员弹窗 -->
    <u-popup :show="openCar" mode="center" round="10" @close="openCar = false">
      <view class="popup-content">
        <view class="popup-header">
          <text class="title">选择驾驶员</text>
          <u-icon name="close" @click="openCar = false"></u-icon>
        </view>
        <choose-people :multiple="true" @chooseUser="getChooseDriver" :deptId="200" @clear="clearChooseDriver" :selected="chooseDriver"></choose-people>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { parseTime } from "@/utils/common.js"
import { complete, rejectTask, returnList, returnTask, getNextFlowNode, delegate, flowTaskForm, } from "@/api/flowable/todo";
import { listCar, getCar } from "@/api/oa/car/car";
import { listCarApproval, getCarApproval, updateCarApproval, addCarApproval, modifyCarApproval } from '@/api/oa/car/carApproval'
import { listProject, getProject } from "@/api/oa/project/project";
import { getUserByRole } from "@/api/system/role";
import { getUsersManageLeader, getUserByPost, getUsersDeptLeader } from '@/api/system/post.js'
import { listUser, getUser } from "@/api/system/user";
import { sendQyMessage } from "@/api/qywx/index";
import FlowNote from '@/pages/components/flowNote.vue';
import ProjectPicker from '@/pages/components/ProjectPicker.vue';
import ProjectInfo from '@/pages/components/ProjectInfo.vue';
import Auditor from "@/pages/components/auditor.vue";
import ChoosePeople from "@/pages/components/ChoosePeople.vue";

export default {
  components: {
    FlowNote,
    ProjectPicker,
    ProjectInfo,
    Auditor,
    ChoosePeople,
  },
  props: {
    taskForm: Object,
    taskName: String,
    startUserName: String,
  },
  data() {
    return {
      form: {
        applyDate: '',
        projectId: '',
        carUsage: '0',
        applyReason: '',
        beginDate: '',
        endDate: '',
        days: 0,
        passengers: 1,
        deptComment: null,
        managerComment: null,
        unionComment: null,
        gmComment: null,
        dszComment: null,
        dispatchComment: null,
        cars: [],
        drivers: [],
        returnDate: '',
        kilometers: '',
        user: {
          nickName: '',
        },
        dept: {
          deptId: '',
          deptName: '',
        },
        applier: '',
      },
      rules: {},
      openProject: false,
      projectObj: {},
      selectedProject: {},
      carUsageOptions: [{
        text: '项目用车',
        value: '0',
        disable: false
      }, {
        text: '非项目用车',
        value: '1',
        disable: false
      }, {
        text: '工会用车',
        value: '2',
        disable: false
      }, {
        text: '党委用车',
        value: '3',
        disable: false
      }, {
        text: '团委用车',
        value: '4',
        disable: false
      }],
      userList: [],
      dept: 0,
      deptUser: '',
      managerUser: '',
      unionUser: '',
      gmUser: '',
      dszUser: '',
      dispatchUser: '',
      deptTime: undefined,
      managerTime: undefined,
      unionTime: undefined,
      gmTime: undefined,
      dszTime: undefined,
      dispatchTime: undefined,
      carList: [],
      chooseDriver: [],
      openCar: false,
      dgtAdvice: '审核意见',
    }
  },
  computed: {
    formRules() {
      return {
        carUsage: {
          rules: [{
            required: this.taskName == '用车申请',
            errorMessage: '请选择申请用途'
          }]
        },
        projectId: {
          rules: [{
            required: this.taskName == '用车申请' && this.form.carUsage == '0',
            errorMessage: '请选择项目'
          }]
        },
        applyReason: {
          rules: [{
            required: this.taskName == '用车申请',
            errorMessage: '请输入用车事由'
          }]
        },
        dateRange: {
          rules: [{
            required: this.taskName == '用车申请',
            errorMessage: '请选择用车时间'
          }]
        },
        passengers: {
          rules: [{
            required: this.taskName == '用车申请',
            errorMessage: '请输入乘车人数'
          }]
        },
        deptComment: {
          rules: [{
            required: this.taskName == '部门审核',
            errorMessage: '请输入部门审核意见'
          }]
        },
        managerComment: {
          rules: [{
            required: this.taskName == '分管审核',
            errorMessage: '请输入分管审核意见'
          }]
        },
        unionComment: {
          rules: [{
            required: this.taskName == '党工团审核',
            errorMessage: '请输入审核意见'
          }]
        },
        gmComment: {
          rules: [{
            required: this.taskName == '总经理审核',
            errorMessage: '请输入总经理审核意见'
          }]
        },
        dszComment: {
          rules: [{
            required: this.taskName == '董事长审核',
            errorMessage: '请输入董事长审核意见'
          }]
        },
        dispatchComment: {
          rules: [{
            required: this.taskName == '安排用车',
            errorMessage: '请输入安排用车意见'
          }]
        },
        cars: {
          rules: [{
            required: this.taskName == '安排用车',
            errorMessage: '请选择车牌号'
          }]
        },
        drivers: {
          rules: [{
            required: this.taskName == '安排用车',
            errorMessage: '请选择驾驶员'
          }]
        },
        returnDate: {
          rules: [{
            required: true,
            errorMessage: '请选择归还日期',
            validateFunction: (rule, value, data, callback) => {
              if (this.taskName === '安排用车' && !value) {
                callback('请选择归还日期');
              } else {
                callback();
              }
            }
          }]
        },
        kilometers: {
          rules: [{
            required: this.taskName == '安排用车',
            errorMessage: '请输入行驶公里'
          }]
        }
      }
    }
  },
  watch: {
    formRules: {
      handler(newVal) {
        this.rules = newVal;
      },
      immediate: true
    }
  },
  created() {
    this.applierUserName = this.startUserName;
    this.getUserList();
    this.initForm();
    this.getCarList();
    this.getDriverList();
  },
  methods: {
    initForm() {
      getCarApproval(this.taskForm.formId).then(res => {
        if (res.data) {
          let data = res.data;
          if (data.carUsage == '2') {
            this.dept = 0;
            this.dgtAdvice = '工会审核意见'
          } else if (data.carUsage == '3') {
            this.dept = 0;
            this.dgtAdvice = '党委审核意见'
          } else if (data.carUsage == '4') {
            this.dept = 0;
            this.dgtAdvice = '团委审核意见'
          }
          if (res.data.drivers) {
            data.drivers = data.drivers.split(',').map(Number);
            this.chooseDriver = [];
            for (let d of data.drivers) {
              getUser(Number(d)).then(res => {
                this.chooseDriver.push(res.data)
              })
            }
          } else {
            data.drivers = []
          }
          if (res.data.cars) {
            data.cars = data.cars.split(',').map(Number);
          } else {
            data.cars = []
          }
          this.form = data;
          if (data.projectId) {
            getProject(data.projectId).then(response => {
              this.projectObj = response.data;
            })
          }
          this.calculateDay();
          this.initAuditor();
        } else {
          this.form.applyDate = parseTime(new Date(), "{y}-{m}-{d}");
          this.form.user.nickName = this.$store.getters.name;
          this.form.applier = this.$store.getters.userId;
          this.form.useDept = this.$store.getters.deptId;
          this.dept = this.$store.getters.deptId;
          this.form.dept.deptName = this.$store.getters.deptName;
        }
      })
    },
    // 获取用户列表
    getUserList() {
      listUser({
        pageNum: 1,
        pageSize: 9999
      }).then(res => {
        if (res.code == 200) {
          this.userList = res.rows
        }
      })
    },
    initAuditor() {

    },
    handleConfirm(project) {
      this.selectedProject = project;
      this.projectObj = project;
      this.form.projectId = project.projectId;
    },
    hanldeChangeType(val) {
      let value = val.detail.value
      if (value == '2' || value == '3' || value == '4') {
        this.dept = 0;
        this.form.projectId = '';
      }
      else
        this.dept = this.$store.getters.deptId;
    },
    handleDateRangeChange(e) {
      if (Array.isArray(e) && e.length === 2) {
        const [start, end] = e;
        this.form.beginDate = start;
        this.form.endDate = end;
        this.form.dateRange = [start, end];
        this.calculateDay();
      }
    },
    calculateDay() {
      if (this.form.beginDate && this.form.endDate) {
        const begin = new Date(this.form.beginDate);
        const end = new Date(this.form.endDate);
        if (!isNaN(begin.getTime()) && !isNaN(end.getTime())) {
          this.form.days = Math.ceil((end - begin) / (1000 * 60 * 60 * 24)) + 1;
        }
      }
    },
    getCarList() {
      listCar({
        pageNum: 1,
        pageSize: 99999999,
      }).then(response => {
        this.carList = response.rows;
      })
    },
    getDriverList() {
      getUserByPost({ postName: '驾驶员' }).then(response => {
        this.driverList = response.data;
      })
    },
    getChooseDriver(val) {
      this.chooseDriver = val;
      if (val.length != 0) {
        let drivers = []
        for (let d of this.chooseDriver) {
          drivers.push(d.userId)
        }
        this.form.drivers = drivers;
      }
      this.openCar = false;
    },
    clearChooseDriver() {
      this.chooseDriver = [];
      this.form.drivers = [];
    },
    submit() {
      this.$refs.form.validate().then(() => {
        this.$modal.confirm('是否提交用车申请？').then(() => {
          this.form.carApplyId = this.taskForm.formId;
          let jsonForm = JSON.stringify(this.form);
          this.form.cars = '';
          this.form.drivers = '';
          addCarApproval(this.form).then((res) => {
            if (res.code == 200) {
              getNextFlowNode({ taskId: this.taskForm.taskId }).then(res => {
                this.getNextFlowNodeApproval().then(() => {
                  uni.showToast({
                    title: '提交成功',
                    icon: 'success'
                  });
                  setTimeout(() => {
                    uni.switchTab({
                      url: '/pages/message/index'
                    });
                  }, 500);
                });
              })
            }
          })
        })
      }).catch(error => {
        console.log(error)
      })
    },
    saves() {
      if (this.taskName == '安排用车') {
        if (!this.form.dispatchComment) {
          uni.showToast({
            title: '请填写安排用车意见',
            icon: 'none'
          });
          return
        }
      }
      let jsonForm = JSON.stringify(this.form);
      modifyCarApproval(jsonForm).then(res => {
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        });
      });
    },
    completeApply() {
      this.$refs.form.validate().then(() => {
        if (this.form.deptComment === '') this.form.deptComment = null;
        if (this.form.managerComment === '') this.form.managerComment = null;
        if (this.form.unionComment === '') this.form.unionComment = null;
        if (this.form.gmComment === '') this.form.gmComment = null;
        if (this.form.dszComment === '') this.form.dszComment = null;
        if (this.form.dispatchComment === '') this.form.dispatchComment = null;
        this.form.formId = this.taskForm.formId;
        this.form.carApplyId = this.taskForm.formId;
        let jsonForm = JSON.stringify(this.form);
        modifyCarApproval(jsonForm).then(res => {
          if (res.code == 200) {
            uni.showModal({
              title: '提示',
              content: '是否提交审批？',
              success: (res) => {
                if (res.confirm) {
                  getNextFlowNode({ taskId: this.taskForm.taskId }).then(res => {
                    const data = res.data;
                    this.getNextFlowNodeApproval().then(() => {
                      uni.showToast({
                        title: '提交成功',
                        icon: 'success'
                      });
                      setTimeout(() => {
                        uni.switchTab({
                          url: '/pages/message/index'
                        });
                      }, 500);
                    });
                  })
                } else {
                  reject(new Error('用户取消提交'));
                }
              }
            });
          }
        })

      }).catch(() => {
        uni.showToast({
          title: '必填项未填写完毕',
          icon: 'none'
        });
      })
    },
    getNextFlowNodeApproval() {
      return new Promise((resolve, reject) => {
        const handleComplete = () => {
          complete(this.taskForm).then(response => {
            uni.showToast({
              title: response.msg,
              icon: 'success'
            });
            resolve();
          }).catch(error => {
            reject(error);
          });
        };

        const setApprovalAndComplete = async (approval) => {
          this.$set(this.taskForm.variables, "approval", approval);
          handleComplete();
          await this.sendQyMessage([approval]);
        };

        const setApprovalListAndComplete = async (approvalList) => {
          let userIds = [];
          if (Array.isArray(approvalList)) {
            userIds = approvalList.map(item => typeof item === 'object' ? item.userId : item);
          }
          this.$set(this.taskForm.variables, "approvalList", approvalList);
          handleComplete();
          await this.sendQyMessage(userIds);
        };

        if (this.taskName == '用车申请') {
          this.$set(this.taskForm.variables, "dept", this.dept);

          if (this.dept == 101) {
            getUserByPost({ postName: '董事长' }).then(async result => {
              await setApprovalAndComplete(result.data[0].userId);
            }).catch(error => {
              reject(error);
            });
          } else if (this.dept == 102) {
            getUserByPost({ postName: '总经理' }).then(async result => {
              await setApprovalAndComplete(result.data[0].userId);
            }).catch(error => {
              reject(error);
            });
          } else if (this.dept == 0) {
            const postName = this.getChooseType();
            getUserByPost({ postName }).then(async result => {
              await setApprovalAndComplete(result.data[0].userId);
            }).catch(error => {
              reject(error);
            });
          } else {
            getUsersDeptLeader({ userId: this.$store.getters.userId }).then(async res => {
              if (res.data) {
                await setApprovalAndComplete(res.data.userId);
              } else {
                reject(new Error('未找到部门领导'));
              }
            }).catch(error => {
              reject(error);
            });
          }
        } else if (this.taskName == '部门审核') {
          getUsersManageLeader({ userId: this.$store.getters.userId }).then(async res => {
            const userIds = res.data.map(user => user.userId);
            await setApprovalListAndComplete(userIds);
          }).catch(error => {
            reject(error);
          });
        } else if (['分管审核', '党工团审核', '总经理审核', '董事长审核'].includes(this.taskName)) {
          getUserByRole({ roleId: 5 }).then(async result => {
            await setApprovalListAndComplete(result.data);
          }).catch(error => {
            reject(error);
          });
        } else if (this.taskName == '安排用车') {
          uni.showModal({
            title: '提示',
            content: '最后一个节点，提交将结束流程，是否提交？',
            success: (res) => {
              if (res.confirm) {
                handleComplete();
              } else {
                reject(new Error('用户取消提交'));
              }
            }
          });
        }
      });
    },
    getChooseType() {
      if (this.form.carUsage == '2') {
        return '党总支书记'
      }
      else if (this.form.carUsage == '3') {
        return '工会主席'
      }
      else
        return '团支部书记'
    },
    showFormItem(name) {
      let isShow = false;
      if (name == '部门审核')
        isShow = (this.dept > 102 && this.taskName == '用车申请') || (this.taskName == '部门审核' || this.taskName == '分管审核') || ((this.taskName == '安排用车' || this.taskName == '') && this.form.deptUserId != null);
      else if (name == '分管审核')
        isShow = (this.dept > 102 && this.taskName == '用车申请') || (this.taskName == '部门审核' || this.taskName == '分管审核') || ((this.taskName == '安排用车' || this.taskName == '') && this.form.managerUserId != null);
      else if (name == '党工团审核')
        isShow = (this.dept == 0 && this.taskName == '用车申请') || this.taskName == '党工团审核' || ((this.taskName == '安排用车' || this.taskName == '') && this.form.unionUserId != null);
      else if (name == '总经理审核')
        isShow = (this.dept == 102 && this.taskName == '用车申请') || this.taskName == '总经理审核' || ((this.taskName == '安排用车' || this.taskName == '') && this.form.gmUserId != null);
      else if (name == '董事长审核')
        isShow = (this.dept == 101 && this.taskName == '用车申请') || this.taskName == '董事长审核' || ((this.taskName == '安排用车' || this.taskName == '') && this.form.dszUserId != null);
      else if (name == '部门审核签名')
        isShow = (this.taskName == '部门审核' || this.taskName == '分管审核') || ((this.taskName == '安排用车' || this.taskName == '') && this.form.deptUserId != null);
      else if (name == '分管审核签名')
        isShow = this.taskName == '分管审核' || ((this.taskName == '安排用车' || this.taskName == '') && this.form.managerUserId != null);
      else if (name == '党工团审核签名')
        isShow = this.taskName == '党工团审核' || ((this.taskName == '安排用车' || this.taskName == '') && this.form.unionUserId != null);
      else if (name == '总经理审核签名')
        isShow = this.taskName == '总经理审核' || ((this.taskName == '安排用车' || this.taskName == '') && this.form.gmUserId != null);
      else if (name == '董事长审核签名')
        isShow = this.taskName == '董事长审核' || ((this.taskName == '安排用车' || this.taskName == '') && this.form.dszUserId != null);
      return isShow;
    },
    handleKilometersInput(val) {
      // 只允许输入数字
      this.form.kilometers = val.replace(/[^\d]/g, '');
    },
    // 发送企业微信消息
    async sendQyMessage(userIds) {
      if (userIds && userIds.length > 0) {
        let formData = new FormData();
        let message = "您有一条新的用车申请:  \n>" + 
        "申请人：<font color='info'>" + this.getUserName(this.form.applier) + "</font> \n>" + 
        "用车事由：" + this.form.applyReason + " \n>" + 
        "开始日期：" + this.form.beginDate + " \n>" + 
        "结束日期：" + this.form.endDate + " \n>" + 
        "乘车人数：" + this.form.passengers + "人 \n>" + 
        "\n>" + 
		"已办流程：<font color='comment'>" + this.taskName + "</font> \n>";
        formData.append('message', message);
        let userString = [];
        for (let u of userIds) {
          let { data } = await getUser(u);
          if (data && data.pinyin) {
            userString.push(data.pinyin);
          }
        }
        formData.append('userString', userString.join('|') + '|YuSiHan|WangRongHua')
        await sendQyMessage(formData);
      }
    },
    // 获取用户名称
    getUserName(userId) {
      if (!userId || !this.userList) return '';
      let user = this.userList.find(u => u.userId == userId);
      return user ? user.nickName : '';
    },

  },
}
</script>

<style lang="scss" scoped>
.form-container {
  padding: 20rpx;
}

.form-title {
  text-align: center;
  margin-bottom: 30rpx;

  .title-text {
    font-size: 36rpx;
    font-weight: bold;
  }

  .title-line {
    height: 2rpx;
    background-color: #eee;
    margin-top: 20rpx;
  }
}

.custom-form {
  .form-item {
    // margin-bottom: 30rpx;
  }
}

.date-range {
  align-items: center;
  gap: 20rpx;
}

.date-text {
  margin: 0 10px;
  font-weight: bold;
}

.car-list {
  padding: 20rpx 0;

  .car-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
  }

  .car-item {
    width: calc(50vw - 50rpx);
    background-color: #f8f8f8;
    border-radius: 12rpx;
    padding: 20rpx;
    transition: all 0.3s;
    margin: 0 3px;
    border: 2rpx solid transparent;

    &:active {
      background-color: #f0f0f0;
    }

    // 选中状态的样式
    &.is-checked {
      background-color: #e6f7ff;
      border-color: #1890ff;
      box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.15);
    }

    .car-info {
      display: flex;
      flex-direction: column;
      gap: 8rpx;

      .car-license {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .car-model {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.driver-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 20rpx;
}

.auditor-info {
  margin-top: 20rpx;
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 24rpx;
}

.popup-content {
  width: 90vw;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 2rpx solid #f5f5f5;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
}
</style>