<template>
  <view class="container">
    <u-collapse :value="['basic']" :border="false">
      <!-- @change=""
		@close=""
		@open="" -->
      <u-collapse-item title="年审" ref="uploadCollapse" name="basic">
        <view class="item">
          <view class="title">车牌号</view>
          <u--input
            border="surround"
            disabled
            v-model="datas.plateNumber"
            fontSize="26"
          ></u--input>
        </view>
        <!-- <view class="item">
          <view class="title">车辆Vin</view>
          <u--input
            border="surround"
            disabled
            v-model="datas.vin"
            fontSize="26"
          ></u--input>
        </view> -->

        <view class="item">
          <view class="title">车辆品牌</view>
          <u--input
            border="surround"
            disabled
            v-model="datas.brandName"
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title">车辆型号</view>
          <u--input
            border="surround"
            disabled
            v-model="datas.modelName"
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title">资产运营城市</view>
          <u--input
            border="surround"
            disabled
            v-model="datas.address"
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title">资产状态</view>
          <u--input
            border="surround"
            disabled
            v-model="datas.truckRentStatusName"
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title">客户</view>
          <u--input
            border="surround"
            disabled
            v-model="datas.customerName"
            fontSize="26"
          ></u--input>
        </view>
        <!-- <view class="item">
          <view class="title required">年审状态</view>
          <u-picker
            :show="showAnnualInspectionStatusPicker"
            :columns="[annualInspectionStatus]"
            keyName="dicName"
            :disabled="disabled"
            :immediateChange="true"
            @confirm="confirmAnnualInspectionStatus"
            @cancel="showAnnualInspectionStatusPicker = false"
          >
          </u-picker>
          <u--input
            border="surround"
            :disabledColor="disabled ? '#f5f7fa' : '#ffffff'"
            disabled
            fontSize="26"
            :value="getAnnualInspectionStatusName(datas.annualInspectionStatus)"
            @tap="!disabled && (showAnnualInspectionStatusPicker = true)"
          >
          </u--input>
        </view> -->
        <view class="item">
          <view class="title">年审到期时间</view>
          <u--input
            border="surround"
            disabled
            :value="formatDateTime(datas.annualInspectionExpireDate, 'minute')"
            fontSize="26"
          ></u--input>
        </view>
        <!-- <view class="item">
          <view class="title">上次年审时间</view>
          <u--input
            border="surround"
            disabled
            :value="formatDateTime(datas.annualReviewLastTime, 'minute')"
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title">年审费用</view>
          <u--input
            border="surround"
            :disabled="disabled"
            v-model="datas.annualInspectionAmount"
            :deletable="!disabled"
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title">提车人</view>
          <u--input
            border="surround"
            :disabled="disabled"
            v-model="datas.vehiclePicker"
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title">联系电话</view>
          <u--input
            border="surround"
            :disabled="disabled"
            v-model="datas.telephone"
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title">维修站</view>
          <u--input
            border="surround"
            disabled
            v-model="datas.maintainSiteName"
            fontSize="26"
          ></u--input>
        </view> -->
        <!-- <view class="item">
          <view class="title required">本次年审时间</view>
          <u-datetime-picker
            placeholder="请选择日期"
            :show="showAnnualReviewTimePicker"
            mode="date"
            @confirm="confirmAnnualReviewTime"
            @cancel="showAnnualReviewTimePicker = false"
          ></u-datetime-picker>
          <u--input
            border="surround"
            :disabledColor="
              disabled || datas.isSubmited ? '#f5f7fa' : '#ffffff'
            "
            fontSize="26"
            disabled
            :value="formatDateTime(datas.annualReviewTime, 'date')"
            @tap="
              !disabled &&
                !datas.isSubmited &&
                (showAnnualReviewTimePicker = true)
            "
          >
          </u--input>
        </view> -->
        <view
          class="item"
          v-if="!datas.isSubmited && !disabled && datas.truckRentStatus == 0"
          style="margin-bottom: 30rpx"
        >
          <button class="btn checkList" @tap="makeTodo">生成异动申请</button>
        </view>
        <!-- <view class="item">
          <view class="title">本次年审公里数</view>
          <u--input
            border="surround"
            :disabled="disabled"
            v-model="datas.annualReviewKilometers"
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title">下次年审公里数</view>
          <u--input
            border="surround"
            :disabled="disabled"
            v-model="datas.annualReviewNextKilometers"
            fontSize="26"
          ></u--input>
        </view> -->
      </u-collapse-item>
    </u-collapse>
    <view class="header" style="margin-top: 15px">费用信息</view>
    <view class="currentItem">
      <view class="item">
        <view class="title required">检测服务站</view>
        <u-picker
          :show="showCheckServicePicker"
          :columns="[checkServiceList]"
          keyName="name"
          :immediateChange="true"
          @confirm="confirmCheckService"
          @cancel="showCheckServicePicker = false"
        >
        </u-picker>
        <u--input
          border="surround"
          :disabledColor="disabled || datas.isSubmited ? '#f5f7fa' : '#ffffff'"
          disabled
          fontSize="26"
          :value="datas.checkServiceName"
          @tap="
            !disabled && !datas.isSubmited && (showCheckServicePicker = true)
          "
        >
        </u--input>
      </view>
      <view class="item">
        <view class="title required">检测服务站费用</view>
        <u-input
          border="surround"
          :disabled="disabled || datas.isSubmited"
          v-model="datas.annualServiceStationAmount"
          fontSize="26"
          type="digit"
        >
        </u-input>
      </view>
      <view class="item ip13noTopBorder">
        <view class="title">检测付款状态</view>
        <u-picker
          :show="showPaymentStatus"
          :columns="[paymentStatusDic]"
          keyName="dicName"
          :disabled="disabled"
          :immediateChange="true"
          @confirm="confirmPaymentStatus"
          @cancel="showPaymentStatus = false"
        >
        </u-picker>
        <u-input
          border="surround"
          :disabledColor="disabled ? '#f5f7fa' : '#ffffff'"
          disabled
          fontSize="26"
          :value="getPaymentStatusName(datas.annualServiceStationPayment)"
          @tap="!disabled && (showPaymentStatus = true)"
        />
      </view>
    </view>
    <view class="currentItem">
      <view class="item">
        <view class="title">二保服务站</view>
        <u-picker
          :show="showSecondServicePicker"
          :columns="[maintainSite]"
          keyName="name"
          :immediateChange="true"
          @confirm="confirmSecond"
          @cancel="showSecondServicePicker = false"
        >
        </u-picker>
        <u--input
          border="surround"
          :disabledColor="disabled || datas.isSubmited ? '#f5f7fa' : '#ffffff'"
          disabled
          fontSize="26"
          :value="datas.secondServiceText"
          @tap="
            !disabled && !datas.isSubmited && (showSecondServicePicker = true)
          "
        >
        </u--input>
      </view>
      <view class="item">
        <view class="title">二保服务站费用</view>
        <u-input
          border="surround"
          :disabled="disabled || datas.isSubmited"
          v-model="datas.maintainSiteAmount"
          fontSize="26"
          type="digit"
        >
        </u-input>
      </view>
      <view class="item ip13noTopBorder">
        <view class="title">二保付款状态</view>
        <u-picker
          :show="showSecondPaymentStatus"
          :columns="[paymentStatusDic]"
          keyName="dicName"
          :disabled="_secondDisabled"
          :immediateChange="true"
          @confirm="confirmSecondPaymentStatus"
          @cancel="showSecondPaymentStatus = false"
        >
        </u-picker>
        <u-input
          class="weInput"
          :style="{ borderColor: borderColor }"
          border="surround"
          :disabledColor="_secondDisabled ? '#f5f7fa' : '#ffffff'"
          disabled
          fontSize="26"
          :value="getPaymentStatusName(datas.maintainSitePayment)"
          @tap="!_secondDisabled && (showSecondPaymentStatus = true)"
        />
      </view>
    </view>
    <view class="currentItem">
      <view class="item">
        <view class="title">整备服务站</view>
        <u-picker
          :show="showReadyServicePicker"
          :columns="[maintainSite]"
          keyName="name"
          :immediateChange="true"
          @confirm="confirmReadyService"
          @cancel="showReadyServicePicker = false"
        >
        </u-picker>
        <u--input
          border="surround"
          :disabledColor="disabled || datas.isSubmited ? '#f5f7fa' : '#ffffff'"
          disabled
          fontSize="26"
          :value="datas.maintenanceStationName"
          @tap="
            !disabled && !datas.isSubmited && (showReadyServicePicker = true)
          "
        >
        </u--input>
      </view>
      <view class="item">
        <view class="title">整备服务站费用</view>
        <u-input
          border="surround"
          :disabled="disabled || datas.isSubmited"
          v-model="datas.maintenanceStationAmount"
          fontSize="26"
          type="digit"
        >
        </u-input>
      </view>
      <view class="item ip13noTopBorder">
        <view class="title">整备付款状态</view>
        <u-picker
          :show="showReadyPaymentStatus"
          :columns="[paymentStatusDic]"
          keyName="dicName"
          :disabled="_readyDisabled"
          :immediateChange="true"
          @confirm="confirmReadyPaymentStatus"
          @cancel="showReadyPaymentStatus = false"
        >
        </u-picker>
        <u-input
          class="weInput"
          :style="{ borderColor: borderColor }"
          border="surround"
          :disabledColor="_readyDisabled ? '#f5f7fa' : '#ffffff'"
          disabled
          fontSize="26"
          :value="getPaymentStatusName(datas.maintenanceStationPayment)"
          @tap="!_readyDisabled && (showReadyPaymentStatus = true)"
        />
      </view>
    </view>
    <view class="header" style="margin-top: 15px">证件信息</view>
    <view class="item">
      <view class="title required">行驶证出证日期</view>
      <u-datetime-picker
        placeholder="请选择行驶证出证日期"
        :show="showAnnualReviewTimePicker"
        mode="date"
        @confirm="confirmAnnualReviewTime"
        @cancel="showAnnualReviewTimePicker = false"
      ></u-datetime-picker>
      <u--input
        border="surround"
        :disabledColor="disabled || datas.isSubmited ? '#f5f7fa' : '#ffffff'"
        fontSize="26"
        disabled
        :value="formatDateTime(datas.annualReviewTime, 'date')"
        @tap="
          !disabled && !datas.isSubmited && (showAnnualReviewTimePicker = true)
        "
      >
      </u--input>
    </view>
    <view class="item">
      <view class="title required">行驶证更新</view>
      <u-upload
        :fileList="fileList13"
        @afterRead="afterRead"
        @delete="deletePic"
        :maxCount="5"
        :width="200"
        :height="200"
        :disabled="disabled || datas.isSubmited"
        :deletable="!disabled && !datas.isSubmited"
        name="13"
      ></u-upload>
    </view>
    <!-- <view class="item">
      <view class="title">附件上传</view>
      <u-upload
        :fileList="fileList12"
        @afterRead="afterRead2"
        @delete="deletePic"
        accept="all"
        uploadIcon="plus"
        @clickPreview="previewFile"
        :previewFullImage="true"
        :maxCount="10"
        :width="155"
        :height="155"
        :disabled="disabled"
        :deletable="!disabled"
        name="12"
      >
      </u-upload>
    </view> -->
    <view class="item">
      <view class="title">营运证出证日期</view>
      <u-datetime-picker
        placeholder="请选择营运证出证日期"
        :show="showYyPicker"
        mode="date"
        @confirm="confirmYy"
        @cancel="showYyPicker = false"
      ></u-datetime-picker>
      <u--input
        border="surround"
        :disabledColor="disabled || datas.isSubmited ? '#f5f7fa' : '#ffffff'"
        fontSize="26"
        disabled
        :value="formatDateTime(datas.operationVerificationDate, 'date')"
        @tap="!disabled && !datas.isSubmited && (showYyPicker = true)"
      >
      </u--input>
    </view>
    <view class="item">
      <view class="title">营运证更新</view>
      <u-upload
        :fileList="fileList12"
        @afterRead="afterRead"
        @delete="deletePic"
        :maxCount="5"
        :width="200"
        :height="200"
        :disabled="disabled || datas.isSubmited"
        :deletable="!disabled && !datas.isSubmited"
        name="12"
      ></u-upload>
    </view>
    <view class="item" v-if="fileList16 && fileList16.length > 0">
      <view class="title">历史营运证查看</view>
      <u-upload
        :fileList="fileList16"
        uploadIcon="plus"
        :disabled="true"
        accept="all"
        :width="155"
        :height="155"
        :deletable="false"
        name="16"
      ></u-upload>
    </view>
    <view class="item" v-for="item in yyPdfList" :key="item.path">
      <view class="line yyBlock">
        <view class="text-small left">{{ item.fileName }}</view>
        <view class="text-small" @tap="previewYyPdf(item)">预览</view>
      </view>
    </view>
    <view class="item">
      <view class="title">二保照片</view>
      <u-upload
        :fileList="fileList14"
        @afterRead="afterRead"
        @delete="deletePic"
        :maxCount="5"
        :width="200"
        :height="200"
        :disabled="disabled || datas.isSubmited"
        :deletable="!disabled && !datas.isSubmited"
        name="14"
      ></u-upload>
    </view>
    <view class="item">
      <view class="title">整备照片</view>
      <u-upload
        :fileList="fileList15"
        @afterRead="afterRead"
        @delete="deletePic"
        :maxCount="5"
        :width="200"
        :height="200"
        :disabled="disabled || datas.isSubmited"
        :deletable="!disabled && !datas.isSubmited"
        name="15"
      ></u-upload>
    </view>
    <view class="item">
      <view class="title">备注</view>
      <u--textarea
        border="surround"
        :deletable="!disabled"
        fontSize="26"
        :disabled="disabled || datas.isSubmited"
        :confirmType="null"
        v-model="datas.remark"
        :placeholder="failureDescPlaceHolder"
      >
      </u--textarea>
    </view>
    <u-loading-page
      bg-color="#ffffff"
      color="#7ba746"
      font-size="24"
      :loading="loading"
      :loading-text="loadingText"
    ></u-loading-page>

    <view class="btns">
      <button
        class="done"
        :class="{ disabled: isRead }"
        :disabled="isRead"
        v-if="!datas.isSubmited"
        @tap="submitConfirm"
      >
        提交
      </button>
      <button
        class="done"
        :class="{ disabled: isRead }"
        :disabled="isRead"
        @tap="save"
      >
        保存
      </button>
      <button class="cancel" @tap="navigateBack">取消</button>
    </view>

    <view style="width: 0px; height: 0px; overflow: hidden">
      <canvas
        :style="
          'width: ' +
          canvasWidth +
          'px; height:' +
          canvasHeight +
          'px;left:8888px'
        "
        canvas-id="myCanvas"
      ></canvas>
    </view>
  </view>
</template>

<script>
import { getUser } from "@/utils/auth.js";
import UniUploadFile from "uni-uploadfile";

export default {
  options: {
    styleIsolation: "shared", // 解除样式隔离
  },

  data() {
    return {
      datas: {
        typeName: "",
        type: [],
        oldRunStatus: null,
        operationAttachment: [],
        maintenanceStationName: "", //整备服务站名称
        checkServiceName: "", //检测服务站名称
        secondServiceText: "", //二保服务站名称
      },
      address: "",
      id: null,
      showAnnualReviewTimePicker: false, // 行驶证出证日期
      showYyPicker: false, // 营运证出证日期
      showAnnualInspectionStatusPicker: false, // 年审状态
      annualInspectionStatus: [], // 年审状态
      paymentStatusDic: [], // 付款状态
      showPlateNumberPicker: false,
      showPaymentStatus: false, // 付款状态是否弹出
      showSecondPaymentStatus: false, // 付款状态是否弹出
      showReadyPaymentStatus: false, // 付款状态是否弹出
      fileList12: [], // 营运证
      fileList16: [], // 历史营运证
      fileList13: [], // 驾驶证照片
      fileList14: [], // 二保
      fileList15: [], // 整备
      stationList: [], // 年审服务站列表
      showCheckServicePicker: false,
      showSecondServicePicker: false,
      showReadyServicePicker: false,
      checkServiceList: [],
      maintainSite: [], // 维修站
      canvasWidth: 0,
      borderColor: "#808080",
      canvasHeight: 0,
      isRead: false, // 页面是否处于阅读模式
      loading: false,
      loadingText: "加载中...",
    };
  },
  methods: {
    previewYyPdf(data) {
      console.log(data);
      if (!data || !data.path) {
        this.alert(`文件上传异常`);
        return;
      }
      console.log(data);
      const path = data.path;
      this.loading = true;
      this.loadingText = "加载中...";
      const that = this;
      uni.downloadFile({
        url: path,
        success: function (res) {
          var filePath = res.tempFilePath;
          that.loading = false;
          uni.openDocument({
            filePath: filePath,
            success: function (res) {
              that.loading = false;
            },
            fail() {
              that.loading = false;
            },
          });
        },
        fail() {
          that.alert("预览文件失败");
          that.loading = false;
        },
      });
    },
    async makeTodo() {
      console.log("makeTodo");
      uni.showModal({
        title: "提示",
        content: "确认生成异动申请吗?",
        success: (res) => {
          if (res.confirm) {
            let params = {
              truckId: this.info.truckId,
              transactionType: 3, //年审
            };
            this.$api.unusualActionApply.addByTruckId(params).then((res) => {
              if (res) {
                uni.showToast({
                  title: "操作成功",
                  icon: "success",
                  duration: 1500,
                });
              }
            });
          }
        },
      });
    },
    async maintainSiteSelect() {
      await this.$api.returnCar.getFixPageList().then((res) => {
        console.log(res);
        this.maintainSite = res;
      });
    },
    // async getStationList() {
    //   await this.$api.annualReview
    //     .queryStationPageList({
    //       pageNo: 1,
    //       pageSize: 100,
    //     })
    //     .then((res) => {
    //       console.log(res);
    //       this.stationList = res.records || [];
    //     });
    // },
    // 整备服务站
    confirmReadyService(e) {
      this.datas.maintenanceStationName = e.value[0].name;
      this.datas.maintenanceStationId = e.value[0].id;
      this.showReadyServicePicker = false;
    },
    // 二保服务站
    confirmSecond(e) {
      this.datas.secondServiceText = e.value[0].name;
      this.datas.maintainSiteId = e.value[0].id;
      this.showSecondServicePicker = false;
    },
    // 检测服务站
    confirmCheckService(e) {
      this.datas.checkServiceName = e.value[0].name;
      this.datas.annualServiceStationId = e.value[0].id;
      this.showCheckServicePicker = false;
    },
    getData() {
      this.$api.annualReview.getTakeId({ id: this.id }).then((res) => {
        this.datas = res;
        //三个数字字段不要出现0.00
        this.datas.annualInspectionAmount =
          !res.annualInspectionAmount || res.annualInspectionAmount === "0.00"
            ? ""
            : res.annualInspectionAmount;
        this.datas.annualReviewNextKilometers =
          !res.annualReviewNextKilometers ||
          res.annualReviewNextKilometers === "0.00"
            ? ""
            : res.annualReviewNextKilometers;
        this.datas.annualReviewKilometers =
          !res.annualReviewKilometers || res.annualReviewKilometers === "0.00"
            ? ""
            : res.annualReviewKilometers;
        this.datas.submitterId = res.submitterId;
        this.datas.checkServiceName =
          this.checkServiceList.find(
            (item) => item.id == this.datas.annualServiceStationId
          )?.name ?? ""; //回显检测服务站名称
        this.datas.secondServiceText =
          this.maintainSite.find((item) => item.id == this.datas.maintainSiteId)
            ?.name ?? ""; //回显二保服务站名称
        this.datas.maintenanceStationName =
          this.maintainSite.find(
            (item) => item.id == this.datas.maintenanceStationId
          )?.name ?? ""; //回显整备服务站名称
        if (!this.isRead) {
          this.datas.implementerName = this.userInfo.userName;
          this.datas.implementer = this.userInfo.id;
        }
        // 根据后端相应的相关图片字段，重新得到fileList用于前端图片预览
        this.parseFileListBack();
      });
    },
    goto(e) {
      uni.navigateTo({ url: e.target.dataset.url });
    },
    navigateBack() {
      uni.navigateBack();
    },
    formatDateTime(obj, type = "date") {
      if (obj == null) {
        return "";
      }
      const date = new Date(obj);

      if (type === "date") {
        let y = 1900 + date.getYear();
        let m = "0" + (date.getMonth() + 1);
        let d = "0" + date.getDate();
        return (
          y +
          "-" +
          m.substring(m.length - 2, m.length) +
          "-" +
          d.substring(d.length - 2, d.length)
        );
      } else if (type === "hour") {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始
        const day = String(date.getDate()).padStart(2, "0");
        const hour = String(date.getHours()).padStart(2, "0");
        return `${year}-${month}-${day} ${hour}:00`;
      } else if (type === "minute") {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始
        const day = String(date.getDate()).padStart(2, "0");
        const hour = String(date.getHours()).padStart(2, "0");
        const minute = String(date.getMinutes()).padStart(2, "0");
        return `${year}-${month}-${day} ${hour}:${minute}`;
      } else {
        throw new Error(
          "Invalid type. Valid types are 'date', 'hour', and 'minute'."
        );
      }
    },
    getNowDateTime() {
      let currentTime = new Date();
      let year = currentTime.getFullYear();
      let month = currentTime.getMonth() + 1;
      let day = currentTime.getDate();
      let hours = currentTime.getHours();
      let minutes = currentTime.getMinutes();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      hours = hours < 10 ? "0" + hours : hours;
      minutes = minutes < 10 ? "0" + minutes : minutes;

      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    getDic() {
      // 年审状态
      this.$api.annualReview.getAnnualInspectionStatusName().then((res) => {
        this.annualInspectionStatus = res;
      });
      // 付款状态
      this.$api.standbyVehicle.getPaymentStatusDic().then((res) => {
        this.paymentStatusDic = res;
      });
      // 维修站名称
      this.$api.annualReview.queryIdNames().then((res) => {
        this.checkServiceList = res;
        console.log(res);
      });
      // 	// 根据id 回显维修站名称
      // 	this.$api.annualReview.queryIdNames().then(res => {
      // 		 const station = res.find(item => item.id === this.datas.annualReviewServiceStationId);
      // 		          if (station) {
      // 		            this.datas.serviceStationName = station.name;
      // 		          }
      // 	})
    },
    // 年审状态
    getAnnualInspectionStatusName(dicCode) {
      return this.getDicValue(this.annualInspectionStatus, dicCode);
    },
    // 付款状态名称
    getPaymentStatusName(dicCode) {
      return this.getDicValue(this.paymentStatusDic, dicCode);
    },
    getDicValue(dic, dicCode) {
      if (dic.length == 0) {
        return "";
      }

      return dic.find((x) => x.dicCode == dicCode)?.dicName ?? "";
    },
    // 营运证出证日期
    confirmYy(e) {
      this.datas.operationVerificationDate = e.value;
      this.showYyPicker = false;
    },
    // 本次年审时间
    confirmAnnualReviewTime(e) {
      this.datas.annualReviewTime = e.value;
      this.showAnnualReviewTimePicker = false;
    },
    // 付款状态
    confirmPaymentStatus(e) {
      this.datas.annualServiceStationPaymentName = e.value[0].dicName;
      this.datas.annualServiceStationPayment = e.value[0].dicCode;
      this.showPaymentStatus = false;
    },
    // 二保付款状态
    confirmSecondPaymentStatus(e) {
      //this.datas.maintainSitePaymentName = e.value[0].dicName;
      this.datas.maintainSitePayment = e.value[0].dicCode;
      this.showSecondPaymentStatus = false;
    },
    // 整备付款状态
    confirmReadyPaymentStatus(e) {
      this.datas.maintenanceStationPaymentName = e.value[0].dicName;
      this.datas.maintenanceStationPayment = e.value[0].dicCode;
      this.showReadyPaymentStatus = false;
    },
    // 年审状态确认
    confirmAnnualInspectionStatus(e) {
      this.datas.annualInspectionStatusName = e.value[0].dicName;
      this.datas.annualInspectionStatus = e.value[0].dicCode;
      this.showAnnualInspectionStatusPicker = false;
    },
    getLocation() {
      uni.getLocation({
        type: "wgs84",
        success: (res) => {
          const longitude = res.longitude;
          const latitude = res.latitude;
          this.$api.truckRent
            .getAddress({ longitude, latitude })
            .then((res) => {
              this.address = res?.data ?? "浙江省嘉兴市";
            });
        },
        fail: (res) => {
          console.log(res);
        },
      });
    },
    checkCameraPermission() {
      console.log("checkCameraPermission");
      uni.getSetting({
        success(res) {
          if (!res.authSetting["scope.camera"]) {
            console.log(`有相机权限`);
            return;
          } else {
            console.log(`没有相机权限! 开始申请获取`);
            this.requestCameraPermission();
          }
        },
        fail(e) {
          console.log(`获取setting失败:\n`, e);
        },
      });
    },
    requestCameraPermission() {
      uni.authorize({
        scope: "scope.camera",
        success() {
          console.log(`相机权限授权成功`);
        },
        fail() {
          console.log(`相机权限授权失败`);
        },
      });
    },
    // 删除图片
    deletePic(event) {
      const fileList = this[`fileList${event.name}`];
      if (fileList.some((x) => x.status == "uploading")) {
        this.alert(`请等待现有图片上传完成后再操作`);
        return;
      }

      this[`fileList${event.name}`].splice(event.index, 1);

      if (event.name == "12") {
        this.datas.newOperationLicencePic.splice(event.index, 1);
      } else if (event.name == "13") {
        this.datas.newDrivingLicensePic.splice(event.index, 1);
      } else if (event.name == "14") {
        this.datas.maintainSitePic.splice(event.index, 1);
      } else if (event.name == "15") {
        this.datas.maintenanceStationPic.splice(event.index, 1);
      }
    },
    // 新增图片
    async afterRead(event) {
      this.loading = true;
      this.loadingText = "添加水印中...";
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      const fileSize = event.file.size / 1024 ** 2; // 图片多少MB
      console.log(`event.file:\n`, event.file);
      for (let i = 0; i < lists.length; i++) {
        let waterUrl = "";
        try {
          waterUrl = await this.addWatermark(lists[i].url, fileSize);
        } catch (e) {
          console.log("添加水印报错\n", e);
          this[`fileList${event.name}`].splice(fileListLen, 1);
          return;
        }
        const result = await this.uploadFilePromise(waterUrl);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result.data?.url ?? "",
            thumb: waterUrl,
          })
        );
        fileListLen++;

        const imgUrl = result.data?.url ?? "";
        if (event.name == "13") {
          this.datas.newDrivingLicensePic.push({
            path: imgUrl,
            fileName: event.file.name,
          });
        } else if (event.name == "12") {
          this.datas.newOperationLicencePic.push({
            path: imgUrl,
            fileName: event.file.name,
          });
        } else if (event.name == "14") {
          //二保照片
          this.datas.maintainSitePic.push({
            path: imgUrl,
            fileName: event.file.name,
          });
        } else if (event.name == "15") {
          //整备照片
          this.datas.maintenanceStationPic.push({
            path: imgUrl,
            fileName: event.file.name,
          });
        }
      }

      this.$nextTick(() => {
        this.$refs.uploadCollapse.init();
      });
    },

    // 新增文件
    // async afterRead2(event) {
    //   console.log(event);
    //   let lists = [].concat(event.file);
    //   let fileListLen = this[`fileList${event.name}`].length;
    //   lists.map((item) => {
    //     this[`fileList${event.name}`].push({
    //       ...item,
    //       status: "uploading",
    //       message: "上传中",
    //     });
    //   });
    //   console.log(`event.file:\n`, event.file);
    //   for (let i = 0; i < lists.length; i++) {
    //     const result = await this.uploadFilePromise2(event.file);
    //     let item = this[`fileList${event.name}`][fileListLen];
    //     this[`fileList${event.name}`].splice(
    //       fileListLen,
    //       1,
    //       Object.assign(item, {
    //         status: "success",
    //         message: "",
    //         url: result.data?.url ?? "",
    //         name: event.file.name,
    //       })
    //     );
    //     fileListLen++;

    //     const url = result.data?.url ?? "";
    //     if (event.name == "12") {
    //       this.datas.newOperationLicencePic.push({
    //         path: url,
    //         fileName: event.file.name,
    //       });
    //     }
    //   }

    //   this.$nextTick(() => {
    //     this.$refs.uploadCollapse.init();
    //   });
    // },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: "/attachment/upload",
          filePath: url,
          name: "file",
          success: (res) => {
            resolve(JSON.parse(res.data || {}));
          },
          fail: (e) => {
            reject(e);
          },
        });
      });
    },
    // 微信原生wx.uploadFile不支持原文件名上传，故手动构造formData请求接口
    // 参考：https://github.com/guoyanshuo/uni-uploadfile
    uploadFilePromise2(file) {
      return new Promise((resolve, reject) => {
        let a = UniUploadFile({
          url: "/attachment/upload",
          files: [file],
          name: "file",
          success: (res) => {
            resolve(res.data || {});
          },
          fail: (e) => {
            reject(e);
          },
        });
      });
    },
    // 图片添加水印
    async addWatermark(img, fileSize) {
      const image = img;
      let res1 = await new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: img,
          success: (res) => {
            // 设置canvas宽高等于原图片宽高
            this.canvasWidth = res.width;
            this.canvasHeight = res.height;
            // 创建 canvas 的绘图上下文
            const ctx = uni.createCanvasContext("myCanvas", this);
            // 绘制图片
            ctx.drawImage(image, 0, 0, res.width, res.height);

            //先加logo
            // const watermarkImg = this.$refs.logo;
            ctx.drawImage("/static/logo3.png", 10, res.height - 150, 200, 40.8);

            //再加时间
            ctx.font = "25px 黑体";
            ctx.fillStyle = "#fff";
            ctx.textAlign = "left";
            ctx.fillText(this.getNowDateTime(), 10, res.height - 70);

            //最后加地址
            ctx.font = "25px 黑体";
            ctx.fillStyle = "#fff";
            ctx.textAlign = "left";
            ctx.fillText(this.address, 10, res.height - 30);
            // 画到 canvas 中
            ctx.draw(false, () => {
              // 将画布转化为图片
              // 设置延时，延时的秒数和图片体积正相关，越大的图片，延时越长
              // 如果不延时，导出的图片可能存在有黑边、只显示部分 等问题
              let timeout = 0;
              if (fileSize <= 3) {
                timeout = 1000;
              } else {
                timeout = 1000 * (fileSize / 3);
              }

              setTimeout(() => {
                uni.canvasToTempFilePath(
                  {
                    canvasId: "myCanvas",
                    fileType: "jpg",
                    quality: fileSize <= 3 ? 1 : 0.75, // 如果不到3MB，则不压缩，否则压缩
                    success: (res) => {
                      console.log(res);
                      this.loading = false;
                      resolve(res.tempFilePath);
                    },
                    fail: (err) => {
                      this.loading = false;
                      reject(err);
                    },
                  },
                  this
                );
              }, timeout);
            });
          },
        });
      });
      return res1;
    },

    parseFileListBack() {
      // this.fileList13 = this.datas.newDrivingLicensePic.map(x => ({ url: x}))
      // 新行驶证照片
      this.fileList13 = this.datas.newDrivingLicensePic.map((x) => ({
        url: x.path,
        name: x.fileName,
      }));
      //   if (this.datas.newDrivingLicensePic !== "") {
      //     // 明确检查是否不是空字符串
      //     this.fileList13 = [{ url: this.datas.newDrivingLicensePic }];
      //   } else {
      //     this.fileList13 = []; // 空字符串情况下设置为空数组
      //   }
      // 附件  25.3.19改为营运证照片
      this.fileList12 = this.datas.newOperationLicencePic.map((x) => ({
        url: x.path,
        name: x.fileName,
      }));
      this.fileList16 = this.datas.operationAttachment?.map((x) => ({
        url: x.path,
        name: x.fileName,
        type: x.fileName.substring(x.fileName.lastIndexOf(".") + 1) || "",
        thumb: "",
      }));

      this.fileList14 = this.datas.maintainSitePic.map((x) => ({
        url: x.path,
        name: x.fileName,
      }));
      this.fileList15 = this.datas.maintenanceStationPic.map((x) => ({
        url: x.path,
        name: x.fileName,
      }));
      this.$nextTick(() => {
        this.$refs.uploadCollapse.init();
      });
    },
    save() {
      //   this.datas.isSubmited = 0;
      // 有id，调用编辑接口
      if (this.datas.isSubmited && !this.check()) {
        return;
      }
      if (this.id) {
        this.$api.annualReview.save(this.datas).then((res) => {
          if (res) {
            uni.showToast({
              title: "保存成功",
              icon: "success",
              duration: 1500,
              success: () => {
                // 使用箭头函数以避免作用域问题
                setTimeout(() => {
                  uni.navigateBack();
                }, 1500);
              },
            });
          }
        });
      }
    },

    submitConfirm() {
      uni.showModal({
        title: "提示",
        content: "确认提交?",
        success: (res) => {
          if (res.confirm) {
            this.submit();
          }
        },
      });
    },

    submit() {
      if (!this.check()) {
        return;
      }

      this.datas.isSubmited = 1;

      // 有id，调用编辑接口
      if (this.id) {
        this.$api.annualReview.save(this.datas).then((res) => {
          if (res) {
            uni.showToast({
              title: "提交成功",
              icon: "success",
              duration: 1500,
              success: () => {
                // 使用箭头函数以避免作用域问题
                setTimeout(() => {
                  uni.navigateBack();
                }, 1500);
              },
            });
          }
        });
      }
    },

    check() {
      console.log(`datas:\n`, this.datas);

      if (
        !this.datas.annualInspectionStatus &&
        this.datas.annualInspectionStatus !== 0
      ) {
        this.alert("请选择年审状态");
        return false;
      }
      if (!this.datas.annualServiceStationId) {
        this.alert("请选择检测服务站");
        return false;
      }
      if (
        this.datas.annualServiceStationAmount === null ||
        this.datas.annualServiceStationAmount === ""
      ) {
        this.alert("请输入检测服务站费用");
        return false;
      }
      //   if (
      //     this.datas.annualServiceStationPayment === null ||
      //     this.datas.annualServiceStationPayment === ""
      //   ) {
      //     this.alert("请选择检测服务站费用付款状态");
      //     return false;
      //   }

      if (
        (this.datas.maintainSiteAmount ||
          this.datas.maintainSitePayment ||
          this.datas.maintainSitePayment === 0) &&
        !this.datas.maintainSiteId
      ) {
        this.alert("请选择二保服务站");
        return false;
      }
      if (
        (this.datas.maintainSiteId ||
          this.datas.maintainSitePayment ||
          this.datas.maintainSitePayment == 0) &&
        (this.datas.maintainSiteAmount === null ||
          this.datas.maintainSiteAmount === "")
      ) {
        this.alert("请输入二保服务站费用");
        return false;
      }
      if (
        (this.datas.maintainSiteId ||
          this.datas.maintainSiteAmount ||
          this.datas.maintainSiteAmount === "0") &&
        !this.datas.maintainSitePayment &&
        this.datas.maintainSitePayment !== 0
      ) {
        this.alert("请选择二保服务站费用付款状态");
        return false;
      }
      if (
        (this.datas.maintenanceStationAmount ||
          this.datas.maintenanceStationPayment ||
          this.datas.maintenanceStationPayment === 0) &&
        !this.datas.maintenanceStationId
      ) {
        this.alert("请选择整备服务站");
        return false;
      }
      if (
        (this.datas.maintenanceStationId ||
          this.datas.maintenanceStationPayment ||
          this.datas.maintenanceStationPayment === 0) &&
        (this.datas.maintenanceStationAmount === null ||
          this.datas.maintenanceStationAmount === "")
      ) {
        this.alert("请输入整备服务站费用");
        return false;
      }
      if (
        (this.datas.maintenanceStationId ||
          this.datas.maintenanceStationAmount ||
          this.datas.maintenanceStationAmount === "0") &&
        !this.datas.maintenanceStationPayment &&
        this.datas.maintenanceStationPayment !== 0
      ) {
        this.alert("请选择整备服务站费用付款状态");
        return false;
      }
      if (!this.datas.annualReviewTime) {
        this.alert("请选择行驶证出证日期");
        return false;
      }
      if (
        !this.datas.newDrivingLicensePic ||
        this.datas.newDrivingLicensePic.length == 0
      ) {
        this.alert("请上传行驶证更新照片");
        return false;
      }
      //   if (!this.datas.operationVerificationDate) {
      //     this.alert("请选择营运证出证日期");
      //     return false;
      //   }
      //   if (
      //     !this.datas.newOperationLicencePic ||
      //     this.datas.newOperationLicencePic.length == 0
      //   ) {
      //     this.alert("请上传营运证更新照片");
      //     return false;
      //   }
      if (
        this.datas.maintainSiteAmount &&
        this.datas.maintainSiteAmount > 0 &&
        (!this.datas.maintainSitePic || this.datas.maintainSitePic.length < 2)
      ) {
        this.alert("请上传至少两张二保照片");
        return false;
      }
      if (
        this.datas.maintenanceStationAmount &&
        this.datas.maintenanceStationAmount > 0 &&
        (!this.datas.maintenanceStationPic ||
          this.datas.maintenanceStationPic.length < 2)
      ) {
        this.alert("请上传至少两张整备照片");
        return false;
      }
      return true;
    },

    alert(msg) {
      uni.showToast({
        title: msg,
        icon: "none",
        duration: 1500,
      });
    },
    // fileDownloadUrl() {
    //   if (!this.datas.signFlowId) {
    //     uni.showToast({
    //       icon: "none",
    //       title: "请先点击签名",
    //       duration: 2000,
    //     });

    //     return;
    //   }

    //   this.loading = true;
    //   this.loadingText = "下载中...";
    //   this.$api.truckRent
    //     .fileDownloadUrl({
    //       signFlowId: this.datas.signFlowId,
    //     })
    //     .then((res) => {
    //       this.loading = false;
    //       if (!res) {
    //         this.alert(`下载失败`);
    //         return;
    //       }
    //       if (res.msg != "OK") {
    //         this.alert(res.msg);
    //         return;
    //       }

    //       this.hasSign = true;
    //     });
    // },
    previewFile(event) {
      console.log("hello");
      const path = event.url;
      this.loading = true;
      this.loadingText = "加载中...";
      const that = this;
      uni.downloadFile({
        url: path,
        success: function (res) {
          var filePath = res.tempFilePath;
          console.log(filePath);
          that.loading = false;
          uni.openDocument({
            filePath: filePath,
            success() {
              that.loading = false;
            },
            fail(e) {
              console.log(e);
              if (e.errMsg == "openDocument:fail filetype not supported") {
                that.alert("微信不支持预览此类文件");
              } else {
                that.alert(e.errMsg);
              }
              that.loading = false;
            },
          });
        },
        fail(e) {
          console.log(e);
          that.alert("预览文件失败");
          that.loading = false;
        },
      });
    },
  },
  computed: {
    disabled() {
      return this.isRead;
    },
    _operationAttachment() {
      return (
        this.datas.operationAttachment?.map((item) => {
          item.fileName = item.path.substring(item.path.lastIndexOf("/") + 1);
          return item;
        }) || []
      );
    },
    yyPdfList() {
      console.log(this._operationAttachment);
      return (
        this._operationAttachment?.filter(
          (item) =>
            !["jpg", "png", "jpeg"].includes(
              item.path.substring(item.path.lastIndexOf(".") + 1)
            )
        ) || []
      );
    },
    _readyDisabled() {
      return (
        this.disabled ||
        (this.datas.isSubmited &&
          ((!this.datas.maintenanceStationAmount &&
            this.datas.maintenanceStationAmount !== "0") ||
            !this.datas.maintenanceStationId))
      );
    },
    _secondDisabled() {
      return (
        this.disabled ||
        (this.datas.isSubmited &&
          ((!this.datas.maintainSiteAmount &&
            this.datas.maintainSiteAmount !== "0") ||
            !this.datas.maintainSiteId))
      );
    },
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id;
    }
    if (options.isRead) {
      this.isRead = Number(options.isRead);
    }
    this.userInfo = getUser() || {};
    this.checkCameraPermission(); // 检测拍照权限
    this.getDic();
    this.maintainSiteSelect(); // 获取维修站点列表
    this.getData();
    // this.getMaintainanceList()
    this.getLocation();
    const windowInfo = wx.getWindowInfo();
    const deviceInfo = wx.getDeviceInfo();
    console.log(windowInfo, deviceInfo);
    if (
      deviceInfo.model &&
      deviceInfo.model.indexOf("iPhone") > -1 &&
      windowInfo.pixelRatio === 3
    ) {
      this.borderColor = "#e7e4e4";
    }
  },
  onPullDownRefresh() {
    uni.stopPullDownRefresh(); //刷新数据之后停止刷新效果
  },
  onShow() {
    if (this.loadingText != "添加水印中...") {
      this.loading = false;
    }
  },
  onHide() {},
  destroyed() {},
  watch: {},
};
</script>

<style lang="less" scoped>
.yyBlock {
  justify-content: space-between;
  display: flex;
  font-size: 26rpx;
}
.container {
  // background-color: #d7d7d7;
  padding: 30rpx;
  .currentItem {
    border: 1px solid #7ba746;
    padding: 0 20rpx 20rpx;
    border-radius: 20rpx;
    margin: 20rpx 0;
  }
  .item {
    margin-top: 30rpx;
    .title {
      font-size: 26rpx;
      margin-bottom: 15rpx;
      &.required::before {
        content: "*";
        color: red;
        margin-right: 3rpx;
      }
    }
    .tip {
      font-size: 26rpx;
      margin-bottom: 15rpx;
      color: #aaaaaa;
      position: relative;
    }
    .btn.checkList {
      width: 200rpx;
      height: 60rpx;
      font-size: 26rpx;
      line-height: 26rpx;
      padding: 17rpx 0;
      text-align: center;
      background-color: #7ba746;
      color: white;
      margin-left: 0;

      &.required::before {
        content: "*";
        color: red;
        margin-right: 3rpx;
      }
    }

    .unit {
      font-size: 26rpx;
    }

    .btn {
      width: 200rpx;
      height: 80rpx;
      margin-left: 0;
      font-size: 26rpx;
      line-height: 26rpx;
      padding: 27rpx 0;
      text-align: center;
      color: white;

      &.sign {
        background-color: #7ba746;
      }

      &.genDocument {
        background-color: #1e98d7;
      }

      &.disabled {
        opacity: 0.6;
      }
    }
  }

  .btns {
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-top: 20rpx;

    button {
      width: 200rpx;
      height: 60rpx;
      font-size: 26rpx;
      line-height: 26rpx;
      padding: 17rpx 0;
      text-align: center;
    }

    .cancel {
      background-color: white;
      color: #7ba746;
      border: 1rpx #7ba746 solid;
    }

    .save {
      background-color: #7ba746;
      color: white;
    }

    .done {
      background-color: #7ba746;
      color: white;
    }

    .disabled {
      opacity: 0.6;
    }
  }
}

/deep/ .u-textarea textarea {
  min-height: 100rpx !important;
  font-size: 26rpx !important;
  white-space: pre-line !important;
}

/deep/ .u-border {
  border-width: 1rpx !important;
  border-color: gray !important;
  border-style: solid;
}

.weInput {
  border: 2rpx solid gray;
  border-radius: 10rpx;
  padding: 13rpx 12rpx;
  color: #303133;
  font-size: 13px;
  //   border-left-width: 1rpx !important;
  //   border-right-width: 1rpx !important;
  //   border-bottom-width: 1rpx !important;
}
// /deep/ .ip13noTopBorder > .u-input {
//   position: relative;
//   padding-top: 6px;
//   padding-bottom: 6px;
//   padding-left: 9px;
//   padding-right: 9px;
// }

// /deep/ .ip13noTopBorder > .u-input::after {
//   content: "";
//   position: absolute;
//   left: 50%;
//   top: 50%;
//   width: 100%;
//   height: 100%;
//   transform: translate(-50%, -50%);
//   border: 0.5px solid gray;
//   border-radius: 4rpx;
// }

/deep/ .u-collapse-item__title {
  padding: 0 !important;
}

/deep/ .u-collapse-item__content {
}
/deep/ .u-collapse-item__content__text {
  padding: unset !important;
  color: unset !important;
  font-size: unset !important;
}

/deep/ .u-cell__title-text {
  font-size: unset !important;
  line-height: unset !important;
  color: unset !important;
}

/deep/ .u-cell__body {
  padding: unset !important;
  font-size: unset !important;
  color: unset !important;
}

/deep/ .u-cell__right-icon-wrap text {
  font-size: 32rpx !important;
}

/deep/ .u-cell--clickable {
  background-color: unset !important;
}

/deep/ .u-collapse-item {
  margin-bottom: 30rpx;
}

/deep/ .uni-select {
  width: 100rpx !important;
}

/deep/ .u-upload__button text {
  font-size: 48rpx !important;
}

/deep/ .u-upload__deletable {
  height: 42rpx !important;
  width: 42rpx !important;
}

/deep/ .u-upload__deletable text {
  font-size: 32rpx !important;
  line-height: 32rpx !important;
}

/deep/ picker-view {
  height: 450rpx !important;
}

/deep/ .uni-select__input-text {
  font-size: 26rpx !important;
  text-align: right !important;
}

/deep/ .uni-select__selector-item text {
  font-size: 26rpx !important;
}

/deep/ .uni-select {
  padding-right: 18rpx !important;
  border-width: 1rpx !important;
  border-color: gray !important;
  border-style: solid !important;
  border-top-width: 0 !important;
  border-right-width: 0 !important;
  border-bottom-width: 0 !important;
}

// /deep/ picker-view picker-view-column:nth-of-type(5) {
// 	display: none;
// }

.changeCarBtn {
  height: 76rpx;
  font-size: 26rpx;
  line-height: 76rpx;
  border-width: 1rpx !important;
  border-color: gray !important;
  border-style: solid !important;
  border-top-width: 0 !important;
  border-right-width: 0 !important;
  border-bottom-width: 0 !important;
}

/* 检查单样式开始 */
/deep/ .td_wrap {
  height: auto !important;
}

/deep/ checkbox-group view.td {
  width: 186rpx !important;
}

/deep/ checkbox-group view.td_wrap {
  width: 186rpx !important;
}

/deep/ .no-bad-table-wrap .td.rowspan {
  display: flex;
  align-items: center;
  justify-content: center;
}

/deep/ .div-table-head .thead .tr view {
  width: 186rpx !important;
}

/deep/ no-bad-table {
  overflow-x: hidden;
}

/deep/ .no-bad-table-wrap .thead .tr .td {
  background-color: #7ba746;
  color: white;
}

/deep/ .no-bad-table-wrap .thead .tr .td .td_wrap {
  background-color: #7ba746;
  color: white;
}
/* 检查单样式结束 */

/* loading 置于顶层 */
/deep/ .u-fade-enter-to.u-fade-enter-active {
  z-index: 10074 !important;
}

/deep/ .selectMultiple .multipleBody .list .item {
  font-size: 26rpx;
}
</style>
