<template>
  <view class="container">
    <u-collapse :value="['basic', 'maintain']" :border="false">
      <u-collapse-item title="基本信息" ref="uploadCollapse" name="basic">
        <!-- <view class="header">基本信息</view> -->
        <view class="item">
          <view class="title required">车牌号</view>
          <u--input
            border="surround"
            :value="info.plateNumber"
            disabled
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title required">车型</view>
          <u--input
            border="surround"
            :value="info.modelName"
            disabled
            fontSize="26"
          ></u--input>
        </view>

        <view class="item">
          <view class="title required">资产运营城市</view>
          <u--input
            border="surround"
            v-model="info.address"
            disabled
            fontSize="26"
          ></u--input>
        </view>
        <view class="item">
          <view class="title required">停车场</view>
          <u-picker
            :show="showParkingPicker"
            :columns="[parkingList]"
            keyName="dicName"
            :immediateChange="true"
            @confirm="confirmPark"
            @cancel="showParkingPicker = false"
          >
          </u-picker>
          <u--input
            border="surround"
            disabledColor="#ffffff"
            disabled
            fontSize="26"
            :value="parkingList[info.parkingSel].dicName"
            @tap="!_disabled && (showParkingPicker = true)"
          >
          </u--input>
        </view>
        <view class="item">
          <view class="title required">仪表盘里程</view>
          <u-input
            border="surround"
            :disabled="_disabled"
            v-model="info.instrumentRange"
            fontSize="26"
            type="digit"
          >
          </u-input>
        </view>
        <view class="item">
          <view class="title required">剩余氢量</view>
          <u-input
            border="surround"
            :disabled="_disabled"
            v-model="info.leftHydrogen"
            fontSize="26"
            type="digit"
            :customStyle="{
              paddingTop: '0',
              paddingBottom: '0',
              paddingRight: '0',
            }"
          >
            <template slot="suffix">
              <uni-section type="line">
                <uni-data-select
                  v-model="info.hydrogenUnit"
                  placeholder="请选择"
                  :localdata="range"
                  @change="changeUnit"
                  :disabled="_disabled"
                ></uni-data-select>
              </uni-section>
            </template>
          </u-input>
          <!-- @change="(value) => (datas.truckList[index].instrumentRange = value)" -->
        </view>
        <view class="item">
          <view class="title required">剩余电量</view>
          <u-input
            border="surround"
            :disabled="_disabled"
            v-model="info.leftElectricity"
            fontSize="26"
            type="digit"
          >
          </u-input>
          <!-- @change="(value) => (datas.truckList[index].instrumentRange = value)" -->
        </view>
        <view class="item">
          <view class="title required">整备类型</view>
          <u-picker
            :show="showPreTypePicker"
            :columns="[preTypeList]"
            keyName="dicName"
            :immediateChange="true"
            @confirm="confirmPreType"
            @cancel="showPreTypePicker = false"
          >
          </u-picker>
          <u--input
            border="surround"
            :disabledColor="_disabled ? '#f5f7fa' : '#ffffff'"
            disabled
            fontSize="26"
            :value="preTypeList[info.preTypeSel].dicName"
            @tap="!_disabled && (showPreTypePicker = true)"
          >
          </u--input>
        </view>
        <view class="item">
          <view class="title required">在库时长（天）</view>
          <u-input
            border="surround"
            disabled
            v-model="info.statusDuration"
            fontSize="26"
            type="digit"
          >
          </u-input>
        </view>
        <view class="item">
          <view class="title"
            >试车时间
            <checkbox-group
              @change="testChange"
              :disabled="_disabled"
              style="margin-left: 30rpx; display: inline-block"
            >
              <checkbox
                :checked="testChecked"
                :disabled="_disabled"
              ></checkbox></checkbox-group
          ></view>
          <u-datetime-picker
            placeholder="请选择日期"
            :disabled="_disabled"
            :show="lastTestRunDatePicker"
            mode="date"
            @confirm="(e) => confirmTestTime(e)"
            @cancel="lastTestRunDatePicker = false"
          ></u-datetime-picker>
          <u--input
            border="surround"
            :disabledColor="_disabled ? '#f5f7fa' : '#ffffff'"
            fontSize="26"
            disabled
            :value="formatDateTime(info.lastTestRunDate, 'date')"
            @tap="!_disabled && (lastTestRunDatePicker = true)"
          >
          </u--input>
        </view>

        <view class="item" style="margin-bottom: 20rpx">
          <button class="btn checkList required" @tap="openCheckListPopup">
            备车检查单
          </button>
        </view>
      </u-collapse-item>
      <view class="header" style="margin-top: 15px">保险信息</view>
      <view class="item">
        <view class="title">商业险到期时间</view>
        <u--input
          border="surround"
          :disabledColor="'#f5f7fa'"
          fontSize="26"
          disabled
          :value="formatDateTime(info.businessInsureExpireDate, 'date')"
        >
        </u--input>
      </view>
      <view class="item">
        <view class="title">交强险到期时间</view>
        <u--input
          border="surround"
          :disabledColor="'#f5f7fa'"
          fontSize="26"
          disabled
          :value="formatDateTime(info.compulsoryInsureExpireDate, 'date')"
        >
        </u--input>
      </view>
      <u-collapse-item title="保养记录" ref="maintainCollapse" name="maintain">
        <!-- <view class="header">日常维护</view> -->
        <u-checkbox-group v-model="checkoutIds" size="36" placement="column">
          <view v-for="(item, index) in info.agentItemListVoList" :key="index">
            <u-cell-group>
              <u-cell :border="false">
                <view slot="title" class="u-slot-title">
                  {{ `序号${index + 1}` }}
                  <view class="viewBtn" @tap="viewRecord(item)"
                    >查看历史记录</view
                  >
                </view>
                <view slot="value" class="u-slot-value">
                  <u-checkbox
                    :customStyle="{ marginBottom: '8px' }"
                    :key="index"
                    :label="` `"
                    :name="item.id"
                  >
                  </u-checkbox>
                </view>
              </u-cell>
              <u-cell
                :border="false"
                title="养护项目"
                :value="item.maintainItem"
              ></u-cell>
              <u-cell
                :border="false"
                :titleStyle="`font-size: 13px;color:${
                  item.maintenanceDueTime &&
                  item.maintenanceDueTime <= new Date().getTime()
                    ? 'red'
                    : ''
                }`"
                title="保养到期时间"
                :value="formatDateTime(item.maintenanceDueTime)"
              ></u-cell>
              <u-cell
                :border="false"
                :titleStyle="`font-size: 13px;color:${
                  info.totalMileage &&
                  item.maintenanceDueMileage &&
                  info.totalMileage > item.maintenanceDueMileage
                    ? 'red'
                    : ''
                }`"
                title="保养到期公里数"
                :value="item.maintenanceDueMileage || ''"
              ></u-cell>
              <u-cell
                :border="false"
                titleStyle="font-size: 13px"
                title="保养公里周期（km）"
                :value="item.kilometerCycle"
              ></u-cell>
              <u-cell
                :border="false"
                titleStyle="font-size: 13px"
                title="保养时间周期（月）"
                :value="item.timeCycle"
              ></u-cell>
            </u-cell-group>
          </view>
        </u-checkbox-group>
      </u-collapse-item>
      <view
        class="item"
        v-if="!_disabled && checkoutIds && checkoutIds.length > 0"
      >
        <button class="btn checkList" @tap="makeTodo">生成保养待办</button>
      </view>
    </u-collapse>

    <!-- <view class="item">
          <view class="title">养护项目</view>
          <view class="line">
            <view class="text-small">{{ item.maintainItem }} </view>
          </view>
        </view> -->
    <!-- <view class="item">
          <view class="title">保养到期时间</view>
          <view class="line">
            <view class="text-small"
              >{{ formatDateTime(item.maintenanceDueTime) }}
            </view>
          </view>
        </view>
        <view class="item">
          <view class="title">保养到期公里数</view>
          <view class="line">
            <view class="text-small"
              >{{ item.maintenanceDueMileage || "" }}
            </view>
          </view>
        </view>
        <view class="item">
          <view class="title">保养公里周期（km）</view>
          <view class="line">
            <view class="text-small">{{ item.kilometerCycle }} </view>
          </view>
        </view>
        <view class="item">
          <view class="title">保养时间周期（月）</view>
          <view class="line">
            <view class="text-small">{{ item.timeCycle }} </view>
          </view>
        </view> -->
    <!-- <view class="item">
      <view class="title font30 required">系统启动检查</view>
      <view class="content">
        <view class="text" v-if="info.preTypeSel === 1">
          隔10天启动车辆1小时以上，检查仪表盘是否有故障灯、空调是否正常、有冷机车辆车冷机温度是否正常，确保电气系统、动力系统正常运转
        </view>
        <view class="text" v-else>
          启动车辆30分钟以上,检查仪表盘是否有故障灯、空调是否正常、有冷机车辆冷机温度是否正常，确保电气系统、动力系统正常运转，混动车辆混动模式能正常运行30分钟
        </view>
        <checkbox-group @change="changeCb1" :disabled="_disabled">
          <checkbox
            :disabled="_disabled"
            value="startupItemCheck"
            :checked="info.startupItemCheck"
          ></checkbox>
        </checkbox-group>
      </view>
    </view>
    <view class="item">
      <view class="title font30 required">油液水检查</view>
      <view class="content">
        <view class="text"> 确保所有油液水加注上线 </view>
        <checkbox-group @change="changeCb2" :disabled="_disabled">
          <checkbox
            value="oilWaterCheck"
            :checked="info.oilWaterCheck"
            :disabled="_disabled"
          ></checkbox>
        </checkbox-group>
      </view>
    </view>
    <view class="item">
      <view class="title font30 required">轮胎检查</view>
      <view class="content">
        <view class="text"> 检查轮胎气压是否正常 </view>
        <checkbox-group @change="changeCb3" :disabled="_disabled">
          <checkbox
            value="tyreCheck"
            :checked="info.tyreCheck"
            :disabled="_disabled"
          ></checkbox
        ></checkbox-group>
      </view>
    </view>
    <view class="item">
      <view class="title font30">试车</view>
      <view class="content">
        <view class="text" v-if="info.preTypeSel === 1">
          混动车辆混动模式能正常运行10分钟
        </view>
        <view class="text" v-else>
          每一个月试车一次，试车公里数为40公里，观察其车况、刹车、转向、燃料电池系统是否有异常
        </view>
        <checkbox-group @change="changeCb4" :disabled="_disabled">
          <checkbox
            value="testRun"
            :checked="info.testRun"
            :disabled="_disabled"
          ></checkbox
        ></checkbox-group>
      </view>
    </view>
    <view class="item">
      <view class="title">试车时间</view>
      <u-datetime-picker
        :show="showTestRunPicker"
        mode="date"
        @confirm="confirmTestRunDate"
        @cancel="showTestRunPicker = false"
      ></u-datetime-picker>
      <u--input
        border="surround"
        :disabledColor="_disabled ? '#f5f7fa' : '#ffffff'"
        disabled
        fontSize="26"
        :value="formatDateTime(info.lastTestRunDate)"
        @tap="!_disabled && (showTestRunPicker = true)"
      >
      </u--input>
    </view> -->
    <!-- <view class="header">保养信息</view>
    <view class="item">
      <view class="title required">下次养护日期</view>
      <u-datetime-picker
        :show="showNextDatePicker"
        mode="date"
        @confirm="confirmNextDate"
        @cancel="showNextDatePicker = false"
      ></u-datetime-picker>
      <u--input
        border="surround"
        :disabledColor="_disabled ? '#f5f7fa' : '#ffffff'"
        disabled
        fontSize="26"
        :value="formatDateTime(info.nextMaintenanceDate)"
        @tap="!_disabled && (showNextDatePicker = true)"
      >
      </u--input>
    </view>
    <view class="item">
      <view class="title required">下次养护公里数</view>
      <u-input
        border="surround"
        v-model="info.nextMaintenanceKilometers"
        fontSize="26"
        :disabled="_disabled"
        type="digit"
      >
      </u-input>
    </view>
    <view class="item">
      <view class="title">下次养护项目</view>
      <u-picker
        :show="showProjectPicker"
        :columns="[projectList]"
        keyName="dicName"
        :immediateChange="true"
        @confirm="confirmProject"
        @cancel="showProjectPicker = false"
      >
      </u-picker>
      <u--input
        border="surround"
        disabledColor="#ffffff"
        disabled
        fontSize="26"
        :value="projectList[info.projectSel].dicName"
        @tap="!_disabled && (showProjectPicker = true)"
      >
      </u--input>
    </view> -->
    <view class="item">
      <view class="title">瑕疵照片</view>
      <u-upload
        :fileList="fileList12"
        @afterRead="afterRead"
        @delete="deletePic"
        :width="200"
        :height="200"
        :disabled="_disabled"
        :deletable="!_disabled"
        name="12"
      ></u-upload>
    </view>
    <view class="item">
      <view class="title">备注</view>
      <u--textarea
        border="surround"
        v-model="info.remark"
        fontSize="26"
        autoHeight
      ></u--textarea>
    </view>
    <view class="btns">
      <button
        class="save"
        :class="{ disabled: _disabled }"
        :disabled="_disabled"
        @tap="editTruckPreparation(false)"
      >
        保存
      </button>
      <button
        class="save"
        :class="{ disabled: _disabled }"
        :disabled="_disabled"
        @tap="editTruckPreparation(true)"
      >
        备车完成
      </button>
      <button class="cancel" @tap="navigateBack">取消</button>
    </view>

    <page-container
      :show="checkListShow"
      :duration="0"
      :overlay="false"
      @beforeleave="checkListShow = false"
    >
      <u-popup
        :show="checkListShow"
        mode="right"
        @close="checkListShow = false"
      >
        <scroll-view scroll-y="true" style="height: 95vh">
          <no-bad-table
            v-if="popupType === 1"
            :columns="columns"
            :list="preparationFormDataList"
            :isRead="_disabled"
            :spanArr="spanArr"
            :slot-cols="['dataCategory', 'dataName', 'takeTruck', 'remark']"
            :span-method="objectSpanMethod"
          >
            <template v-slot="{ row, col, index, isRead }">
              <view
                v-if="col.key == 'dataCategory'"
                style="white-space: pre-wrap"
              >
                {{ row.dataCategory }}
              </view>
              <view
                v-else-if="col.key == 'dataName'"
                style="white-space: pre-wrap"
              >
                {{ row.dataName }}
              </view>
              <view
                v-else-if="col.key == 'takeTruck'"
                style="display: flex; justify-content: center"
              >
                <u-switch
                  size="50"
                  v-model="row.takeTruck"
                  :disabled="isRead"
                  @change="switchTakeTruck(index)"
                  inactiveColor="#f5f7fa"
                  activeColor="#7ba746"
                >
                </u-switch>
              </view>
              <view
                v-else-if="col.key == 'remark' && !row.notUpdate"
                style="display: flex; justify-content: center"
              >
                <u--input
                  border="surround"
                  fontSize="26"
                  :disabled="isRead"
                  :value="row.remark"
                  @change="inputQuality($event, index)"
                >
                </u--input>
              </view>
            </template>
          </no-bad-table>
          <viwe v-else>
            <view
              v-for="(item, index) in recordList"
              class="truckItem"
              :key="index"
            >
              <view style="text-align: center">{{
                item.maintainItem + "保养"
              }}</view>
              <view class="border">
                <view class="flexWrap">
                  <view class="item" style="margin-right: 56rpx">
                    <u-cell-group :border="false">
                      <u-cell
                        :border="false"
                        title="工时费"
                        titleStyle="font-size: 13px"
                        :value="item.hourFee"
                      ></u-cell>
                      <u-cell
                        :border="false"
                        titleStyle="font-size: 13px"
                        title="材料费"
                        :value="item.materialsExpenses"
                      ></u-cell>
                    </u-cell-group>
                  </view>
                  <view class="item">
                    <u-cell-group :border="false">
                      <u-cell
                        :border="false"
                        titleStyle="font-size: 13px"
                        title="材料费(公司自采)"
                        :value="item.companyMaterialsExpenses"
                      ></u-cell>
                      <u-cell
                        :border="false"
                        title="合计"
                        titleStyle="font-size: 13px"
                        :value="item.totalFee"
                      ></u-cell>
                    </u-cell-group>
                  </view>
                </view>
                <u-cell-group :border="false">
                  <u-cell
                    :border="false"
                    title="维修站"
                    titleStyle="font-size: 13px"
                    :value="item.maintainSiteName"
                  ></u-cell>
                  <u-cell
                    :border="false"
                    titleStyle="font-size: 13px"
                    title="实际保养日期"
                    :value="formatDateTime(item.actualMaintenanceDate)"
                  ></u-cell>
                  <u-cell
                    :border="false"
                    titleStyle="font-size: 13px"
                    title="实际保养公里数"
                    :value="item.actualMaintenanceMileage || ''"
                  ></u-cell>
                  <u-cell
                    :border="false"
                    titleStyle="font-size: 13px"
                    title="负责人"
                    :value="item.handlerName"
                  ></u-cell>
                </u-cell-group>
              </view>
            </view>
          </viwe>

          <view class="btns">
            <button
              class="save"
              v-if="!isRead && popupType === 1"
              @tap="saveFormDataList"
            >
              保存
            </button>
            <button class="cancel" @tap="cancelFormDataChange">取消</button>
          </view>
        </scroll-view>
      </u-popup>
    </page-container>
    <view style="width: 0px; height: 0px; overflow: hidden">
      <canvas
        :style="
          'width: ' +
          canvasWidth +
          'px; height:' +
          canvasHeight +
          'px;left:8888px'
        "
        canvas-id="myCanvas"
      ></canvas>
    </view>
    <u-loading-page
      bg-color="#ffffff"
      color="#7ba746"
      font-size="24"
      :loading="loading"
      :loading-text="loadingText"
    ></u-loading-page>
  </view>
</template>

<script>
export default {
  options: {
    styleIsolation: "shared", // 解除样式隔离
  },
  data() {
    return {
      id: 0,
      info: {
        parkingSel: null,
        projectSel: null,
        preTypeSel: null,
        // instrumentRange: null,
        // startupItemCheck: false, // 日常维护选中列表
        // oilWaterCheck: false, // 日常维护选中列表
        // tyreCheck: false, // 日常维护选中列表
      }, // 该备车车辆记录的数据
      preTypeList: [], // 整备类型列表
      parkingList: [], //停车场列表
      projectList: [], //养护项目列表
      truckType: [],
      isRead: false,
      showPreTypePicker: false, // 整备类型弹窗
      showParkingPicker: false,
      showProjectPicker: false, // 养护项目弹窗
      showNextDatePicker: false, // 养护时间弹窗
      showTestRunPicker: false, // 试车时间弹窗
      prepareOk: false, // 备车完成 switch
      checkListShow: false, // 检查单弹窗
      popupType: 1, // 弹窗类型 1:备车检查单 2:保养记录
      preparationFormDataList: [], // 备车单数据
      spanArr: [],
      columns: [
        {
          title: "检查类别",
          key: "dataCategory",
        },
        {
          title: "检查项目",
          key: "dataName",
        },
        {
          title: "选择",
          key: "takeTruck",
        },
        {
          title: "备注",
          key: "remark",
        },
      ],
      range: [
        { value: 1, text: "%" },
        { value: 2, text: "MPa" },
        { value: 3, text: "kg" },
      ],
      inStoreList: [], // 在库状态车辆列表
      lastTestRunDatePicker: false, // 试车时间
      checkoutIds: [], // 检查单选中项
      testChecked: false, // 试车时间复选框
      recordList: [], // 保养记录列表
      canvasWidth: 0,
      canvasHeight: 0,
      loading: false,
      loadingText: "加载中...",
      address: "", // 水印位置
      fileList12: [],
    };
  },
  computed: {
    _disabled() {
      return this.isRead;
    },
  },
  async onLoad(options) {
    if (options.id) {
      this.id = options.id;
    }
    if (options.isRead) {
      this.isRead = Number(options.isRead);
    }
    await this.getParkList(); // 获取停车场列表
    await this.getPreTypeList(); // 获取整备类型列表
    this.getData();
    this.getLocation();
  },
  methods: {
    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);
        },
      });
    },
    // 新增图片
    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 == "12") {
          this.info.blemish.push({
            path: imgUrl,
            fileName: event.file.name,
          });
        }
      }

      this.$nextTick(() => {
        this.$refs.uploadCollapse.init();
      });
    },
    // 删除图片
    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.info.blemish.splice(event.index, 1);
      }
    },
    //水印时间
    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}`;
    },
    // 图片添加水印
    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;
    },
    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);
          },
        });
      });
    },
    viewRecord(row) {
      this.$api.maintainTodo
        .getRecords({
          truckId: this.info.truckId,
          maintainItemId: row.id,
        })
        .then((res) => {
          console.log(`res:`, res);
          this.recordList =
            res?.data.map((item) => {
              item.totalFee =
                Number(item.hourFee || 0) +
                (Number(item.materialsExpenses) || 0) +
                (Number(item.companyMaterialsExpenses) || 0);
              return item;
            }) || [];
          this.popupType = 2; // 保养记录
          this.checkListShow = true;
          uni.setNavigationBarTitle({
            title: "保养记录",
          });
        });
    },
    makeTodo() {
      console.log("makeTodo");
      console.log(this.checkoutIds);
      //现在itemList的id或者maintainItemId是空的 checkoutIds也是空的做不了过滤
      uni.showModal({
        title: "提示",
        content: "确认生成保养代办吗?",
        success: (res) => {
          if (res.confirm) {
            let params = {
              truckId: this.info.truckId,
              itemList: this.info.agentItemListVoList.filter((item) =>
                this.checkoutIds.includes(item.id)
              ),
            };
            this.$api.maintainTodo.add(params).then((res) => {
              if (res) {
                uni.showToast({
                  title: "操作成功",
                  icon: "success",
                  duration: 1500,
                });
              }
            });
          }
        },
      });
    },
    checkboxChange(n) {
      console.log("change", n);
    },
    // 试车时间
    confirmTestTime(e) {
      this.info.lastTestRunDate = e.value;
      this.lastTestRunDatePicker = false;
    },
    testChange(e) {
      console.log(e);
      console.log(this.info.lastTestRunDate);
      if (e?.detail?.value && e?.detail?.value.length) {
        this.oldLastTestRunDate = this.info.lastTestRunDate;
        this.info.lastTestRunDate = new Date().getTime();
      } else {
        this.info.lastTestRunDate = this.oldLastTestRunDate;
      }
    },
    changeUnit(e) {
      this.info.hydrogenUnit = e;
    },
    // changeCb1(e) {
    //   if (e.detail.value.length > 0) {
    //     this.info.startupItemCheck = 1;
    //   } else {
    //     this.info.startupItemCheck = 0;
    //   }
    // },
    // changeCb2(e) {
    //   if (e.detail.value.length > 0) {
    //     this.info.oilWaterCheck = 1;
    //   } else {
    //     this.info.oilWaterCheck = 0;
    //   }
    // },
    // changeCb3(e) {
    //   if (e.detail.value.length > 0) {
    //     this.info.tyreCheck = 1;
    //   } else {
    //     this.info.tyreCheck = 0;
    //   }
    // },
    // changeCb4(e) {
    //   if (e.detail.value.length > 0) {
    //     this.info.testRun = 1;
    //     this.info.lastTestRunDate = new Date().getTime();
    //   } else {
    //     this.info.testRun = 0;
    //   }
    // },
    async getParkList() {
      await this.$api.returnCar
        .getParkingPageList({
          pageNo: 1,
          pageSize: 999,
        })
        .then((res) => {
          if (res) {
            let datas = res?.data;
            this.parkingList = datas.records.map((item) => {
              return {
                dicCode: item.id,
                dicName: item.parkingName,
              };
            });
          }
        });
    },
    async getPreTypeList() {
      this.$api.truckPreparation.getPreTypeList().then((res) => {
        console.log(`res:`, res);
        this.preTypeList = res;
      });
    },
    getData() {
      this.$api.truckPreparation.getById({ id: this.id }).then((res) => {
        if (res.code != 200) {
          return;
        }

        console.log(`res:`, res.data);
        this.info = res.data;
        this.info.agentItemListVoList = res.data?.agentItemListVoList?.map(
          (item) => {
            item.totalMileage = this.info.instrumentRange || 0;
            item.maintainItemId = item.id;
            return item;
          }
        );
        const parkingIndex =
          this.parkingList.findIndex(
            (item) => item.dicCode == res.data?.parkingId
          ) ?? "";
        this.$set(this.info, "parkingSel", parkingIndex); //set大法好
        const preTypeIndex =
          this.preTypeList.findIndex(
            (item) => item.dicCode == res.data?.preparationType
          ) ?? "";
        this.$set(this.info, "preTypeSel", preTypeIndex); //set大法好

        // const projectIndex =
        //   this.projectList.findIndex(
        //     (item) => item.dicCode == res.data?.projectId
        //   ) || "";

        // this.$set(this.info, "projectSel", projectIndex); //set大法好
        this.preparationFormDataList = this.processFormDataList(
          this.deepClone(this.info.preparationFormDataList)
        );
        this.getSpanArr(this.preparationFormDataList);
        this.fileList12 = this.info.blemish.map((x) => ({
          url: x.path,
          name: x.fileName,
        }));
        this.$nextTick(() => {
          this.$refs.uploadCollapse.init();
          this.$refs.maintainCollapse.init();
        });
        // console.log(`this.info:\n`, this.info)
        console.log(
          `this.preparationFormDataList:\n`,
          this.preparationFormDataList
        );
      });
    },
    //试车时间
    confirmTestRunDate(e) {
      this.info.lastTestRunDate = e.value;
      this.showTestRunPicker = false;
    },
    //养护时间
    confirmNextDate(e) {
      this.info.nextMaintenanceDate = e.value;
      this.showNextDatePicker = false;
    },
    //整备类型确认
    confirmPreType(e) {
      this.info.preTypeSel = e.indexs[0];
      this.showPreTypePicker = false;
    },
    //项目确认
    confirmProject(e) {
      this.info.projectSel = e.indexs[0];
      this.showProjectPicker = false;
    },
    //停车场确认
    confirmPark(e) {
      this.info.parkingSel = e.indexs[0];
      this.showParkingPicker = false;
    },
    getDicValue(dic, dicCode) {
      if (dic.length == 0) {
        return "";
      }

      return dic.find((x) => x.dicCode == dicCode)?.dicName ?? "";
    },
    formatDateTime(obj, type = "date") {
      if (obj == null) {
        return "";
      }
      // 精确到日
      if (type == "date") {
        let date = new Date(obj);
        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 date = new Date(obj); // 将时间戳转换为毫秒
        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`;
      }
    },
    timestampToDateAndBack(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以要+1
      const day = date.getDate().toString().padStart(2, "0");
      const formattedDate = `${year}-${month}-${day}`;
      const newTimestamp = new Date(`${formattedDate} 00:00:00`).getTime();
      return newTimestamp;
    },
    getNowTimestamp() {
      // 获取当前时间精确到小时的时间戳
      const now = new Date();
      now.setMinutes(0, 0, 0); // 设置分钟、秒、毫秒为0
      return now.getTime(); // 返回时间戳
    },
    confirmBand(e) {
      console.log(e);
      const brand = e.value[0].dicCode;
      // 没有更改
      if (brand == this.info.brand) {
        this.showParkingPicker = false;
        return;
      }
      this.info.brand = brand;
      this.showParkingPicker = false;
      this.info.plateNumber = "";
      this.info.vin = "";
      this.info.hasTailboard = "";
      this.info.hasAdvertisement = "";
      this.info.isHang = "";
    },
    navigateBack() {
      uni.navigateBack();
    },
    switchTakeTruck(index) {
      this.preparationFormDataList[index].takeTruck =
        !this.preparationFormDataList[index].takeTruck;
    },
    inputQuality(value, index) {
      this.preparationFormDataList[index].remark = value;
    },
    processFormDataList(dataList) {
      dataList = dataList.filter((x) => x.dataName != "检查项目");
      for (let item of dataList) {
        if (item.takeTruck == "true") {
          item.takeTruck = true;
        } else if (item.takeTruck == "false") {
          item.takeTruck = false;
        }
      }

      return dataList;
    },
    // https://www.cnblogs.com/janni/p/12992591.html
    getSpanArr(data) {
      this.spanArr = [];
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同 dataCategory (类别字段)
          if (data[i].dataCategory === data[i - 1].dataCategory) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
          }
        }
      }
    },
    objectSpanMethod(row, column, rowIndex, columnIndex) {
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    // https://www.kancloud.cn/uview/uview-ui_v2/2579089
    deepClone(obj) {
      if (obj === null) return null;
      if (typeof obj !== "object") return obj;
      if (obj instanceof Date) {
        let date = new Date();
        date.setTime(obj.getTime());
        return date;
      }
      if (obj instanceof RegExp) {
        let re = new RegExp(obj.source);
        re.lastIndex = obj.lastIndex;
        return re;
      }
      let newObj = new obj.constructor();
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          newObj[key] = this.deepClone(obj[key]);
        }
      }
      return newObj;
    },
    openCheckListPopup() {
      this.popupType = 1; //  备车检查单
      if (this.info.preparationFormDataList.length == 0) {
        this.$api.standbyVehicle
          .getFormDataListByTruckId({ id: this.info.truckId })
          .then((res) => {
            this.preparationFormDataList = this.processFormDataList(res.data);
            this.getSpanArr(this.preparationFormDataList);
            this.checkListShow = true;
            uni.setNavigationBarTitle({
              title: "备车检查单",
            });
          });
      } else {
        this.checkListShow = true;
        uni.setNavigationBarTitle({
          title: "备车检查单",
        });
      }
    },
    saveFormDataList() {
      this.checkListShow = false;
      this.info.preparationFormDataList = this.deepClone(
        this.preparationFormDataList
      );
      console.log(this.info.preparationFormDataList);
      uni.setNavigationBarTitle({
        title: "备车信息",
      });
    },
    cancelFormDataChange() {
      if (this.popupType === 1) {
        // 备车检查单需要重置
        this.preparationFormDataList = this.processFormDataList(
          this.deepClone(this.info.preparationFormDataList)
        );
        this.getSpanArr(this.preparationFormDataList);
      }
      this.checkListShow = false;
      uni.setNavigationBarTitle({
        title: "备车信息",
      });
    },

    // 在提交前检查，是否有必填字段未填写
    check() {
      if (this.info.parkingSel === null || this.info.parkingSel === -1) {
        this.alert("请选择停车场");
        return false;
      }
      if (!this.info.instrumentRange) {
        this.alert("请填写仪表盘里程");
        return false;
      }
      if (!this.info.leftHydrogen) {
        this.alert("请填写剩余氢量");
        return false;
      }
      if (!this.info.hydrogenUnit) {
        this.alert("请选择氢量单位");
        return false;
      }
      if (!this.info.leftElectricity) {
        this.alert("请填写剩余电量");
        return false;
      }
      if (this.info.preTypeSel === null || this.info.preTypeSel === -1) {
        this.alert("请选择整备类型");
        return false;
      }
      //   if (!this.info.startupItemCheck) {
      //     this.alert("请勾选系统启动检查");
      //     return false;
      //   }
      //   if (!this.info.oilWaterCheck) {
      //     this.alert("请勾选油液水检查");
      //     return false;
      //   }
      //   if (!this.info.tyreCheck) {
      //     this.alert("请勾选轮胎检查");
      //     return false;
      //   }
      //   if (!this.info.nextMaintenanceDate) {
      //     this.alert("请选择下次养护日期");
      //     return false;
      //   }
      //   if (!this.info.nextMaintenanceKilometers) {
      //     this.alert("请填写下次养护公里数");
      //     return false;
      //   }
      //   if (this.info.projectSel === null) {
      //     this.alert("请选择下次养护项目");
      //     return false;
      //   }
      return true;
    },
    alert(msg) {
      uni.showToast({
        title: msg,
        icon: "none",
        duration: 1500,
      });
    },
    // 保存备车信息表
    editTruckPreparation(submit = false) {
      if (submit && !this.check()) {
        return;
      }
      console.log(this.info);
      let params = { ...this.info };
      params.submit = submit;
      if (params.parkingSel !== -1)
        params.parkingId = this.parkingList[params.parkingSel].dicCode;
      if (params.preTypeSel !== null)
        params.preparationType = this.preTypeList[params.preTypeSel].dicCode;
      //   params.projectId = this.projectList[params.projectSel].dicCode;
      this.$api.truckPreparation.editTruckPreparation(params).then((res) => {
        // todo： res是接口data数据，之后研究一下如何获取整个内容
        if (res) {
          uni.showToast({
            title: submit ? "备车成功" : "保存成功",
            icon: "success",
            duration: 1500,
            success() {
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            },
          });
        }
      });
    },
  },
  onPullDownRefresh() {
    uni.stopPullDownRefresh(); //刷新数据之后停止刷新效果
  },
};
</script>

<style lang="less" scoped>
.truckItem {
  margin-top: 30rpx;
  padding: 30rpx;
  .border {
    margin-top: 10rpx;
    border: 1px solid #7ba746;
    border-radius: 20rpx;
    padding: 0 20rpx;
  }
  .flexWrap {
    display: flex;
    .item {
      margin-top: 0;
      flex: 1;
    }
  }
}
.viewBtn {
  display: inline-block;
  font-size: 26rpx;
  padding: 5rpx 10rpx;
  border-radius: 10rpx;
  margin-left: 10rpx;
  background: #7ba746;
  color: #fff;
}
/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/ .uni-select__input-text {
  font-size: 26rpx !important;
  text-align: right !important;
}
/deep/ .u-collapse-item__content__text {
  padding: unset !important;
  color: unset !important;
  font-size: unset !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/ .uni-select {
  width: 100rpx !important;
}
.container {
  // background-color: #d7d7d7;
  padding: 30rpx;
  .header {
    margin: 15rpx 0;
  }
  .item {
    margin-top: 30rpx;
    .content {
      font-size: 26rpx;
      color: #797979;
      display: flex;
      gap: 50rpx;
      justify-content: space-between;
      margin-bottom: 10rpx;
      .text {
        border: 2rpx solid #797979;
        border-radius: 10rpx;
        padding: 5rpx;
      }
    }
    .title {
      font-size: 26rpx;
      margin-bottom: 15rpx;

      &.required::before {
        content: "*";
        color: red;
        margin-right: 3rpx;
      }
    }
    .font30 {
      font-size: 30rpx;
    }
    .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;
      }
    }
  }

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

    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;
    }
    .disabled {
      opacity: 0.6;
    }
  }
}

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

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

/deep/ .u-switch {
  border-color: rgba(0, 0, 0, 0.12) !important;
}

/deep/ .u-slide-right-enter-to.u-slide-right-enter-active {
  width: 750rpx;
}

/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;
}
</style>
