<template>
  <uni-card
    :shadow="'0rpx 0rpx 10rpx 0rpx rgba(5,68,37,0.12)'"
    :padding="'0px'"
    :margin="'20px'"
    :border="false"
  >
    <view class="title">车辆信息</view>
    <u-form
      labelPosition="left"
      :model="model1"
      :rules="rules"
      ref="form"
      :labelWidth="80"
      :labelStyle="{ padding: '0rpx 10rpx' }"
      :errorType="'border-bottom'"
    >
      <u-form-item
        :prop="`formData.${item.key}`"
        :label="item.name"
        :required="item.required"
        v-for="(item, index) in formAttrList"
        :key="index"
        @click="item.fn"
      >
        <u-input
          v-if="item.type === 'input'"
          v-model="(model1.formData as any)[item.key]"
          :placeholder="`请输入${item.name}`"
          clearable
          :customStyle="{}"
          border="none"
          :disabled="item.disabled"
          :type="
            ['contactInfo', 'curbWeight'].indexOf(item.key) > -1
              ? 'number'
              : 'text'
          "
        >
          <template #suffix>
            <text v-if="item.unit">
              {{ item.unit }}
            </text>
          </template>
        </u-input>
        <u-input
          v-if="item.type === 'select'"
          :disabled="true"
          :disabledColor="'#ffffff'"
          v-model="(model1.formData as any)[item.key]"
          :placeholder="`请选择${item.name}`"
          clearable
          :customStyle="{}"
          border="none"
        >
          <template #suffix>
            <text v-if="item.unit">
              {{ item.unit }}
            </text>
          </template>
        </u-input>

        <!-- 上传 -->
        <view v-if="item.type === 'upload'">
          <view>（拍照上传后自动识别车辆信息）</view>
          <view style="padding-left: 20rpx; margin-top: 20rpx">
            <image
              @click="handleUpload"
              :src="
                model1.formData.licensePhotoUrl ||
                `${url}/static/img/vehicle/upload.png`
              "
              style="width: 203rpx; height: 133rpx"
            />
          </view>
          <view style="padding-left: 20rpx; margin-top: 10rpx"
            >点击上传行驶证主页</view
          >
        </view>
        <template #right v-if="item.type === 'select'">
          <u-icon name="arrow-right" @click="item.fn"></u-icon>
        </template>
      </u-form-item>
    </u-form>
  </uni-card>

  <view class="btn-box-fix-btn">
    <view
      ><u-button type="primary" shape="circle" @click="save"
        >提交询价</u-button
      ></view
    >
  </view>

  <block v-for="(item, index) in formAttrList" :key="index">
    <u-action-sheet
      v-if="item.type === 'select' && item.childKey"
      :actions="contrlModalParams[item.childKey].list"
      :title="contrlModalParams[item.childKey].title"
      :show="contrlModalParams[item.childKey].isShow"
      @select="(v: any) => handleSelect(item.childKey, v)"
      @close="contrlModalParams[item.childKey].isShow = false"
      :closeOnClickAction="true"
    ></u-action-sheet>
  </block>
</template>

<script setup lang="ts">
import { url } from "@/utils/data";
import { PictureApi, VehicleApi, UserApi } from "@/services";
import pinia from "@/store";
import { useMemberStore } from "@/store/index";
import valid from "@/utils/validate";
const store = useMemberStore(pinia);
const model1 = reactive<any>({
  formData: {},
});
const formAttrList = reactive<any>([
  {
    name: "姓名",
    key: "name",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "联系方式",
    key: "contactInfo",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "行驶证",
    key: "",
    type: "upload",
    required: false,
    unit: "",
  },

  {
    name: "车辆类型",
    key: "vehicleType",
    type: "select",
    childKey: "vehicleType",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams["vehicleType"].isShow = true;
    },
  },
  {
    name: "燃油类别",
    key: "fuelType",
    type: "select",
    childKey: "fuelType",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams["fuelType"].isShow = true;
    },
  },
  {
    name: "钢圈材质",
    key: "wheelMaterial",
    type: "select",
    childKey: "material",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams["material"].isShow = true;
    },
  },
  {
    name: "整备质量",
    key: "curbWeight",
    type: "input",
    required: true,
    unit: "KG",
  },
  {
    name: "车架号",
    key: "vin",
    type: "input",
    required: false,
    unit: "",
  },
  {
    name: "品牌型号",
    key: "brandModel",
    type: "input",
    required: false,
    unit: "",
  },
  {
    name: "系列",
    key: "series",
    type: "input",
    required: false,
    unit: "",
  },
]);
const rules = reactive({
  "formData.name": {
    type: "string",
    required: true,
    message: "请输入姓名",
    trigger: ["blur", "change"],
  },
  "formData.contactInfo": {
    type: "string",
    required: true,
    message: "请输入联系方式",
    trigger: ["blur", "change"],
  },
  "formData.licensePhotoUrl": {
    type: "string",
    required: true,
    message: "请上传行驶证照片",
    trigger: ["blur", "change"],
  },
  "formData.vehicleType": {
    type: "string",
    required: true,
    message: "请选择车辆类型",
    trigger: ["blur", "change"],
  },
  "formData.fuelType": {
    type: "string",
    required: true,
    message: "请选择燃油类型",
    trigger: ["blur", "change"],
  },
  "formData.wheelMaterial": {
    type: "string",
    required: true,
    message: "请选择钢圈材质",
    trigger: ["blur", "change"],
  },
  "formData.curbWeight": {
    type: "string",
    required: true,
    message: "请输入整备质量",
    trigger: ["blur", "change"],
  },
});

const contrlModalParams = reactive<any>({
  vehicleType: {
    isShow: false,
    title: "车辆类型",
    list: [
      { name: "轿车（含MPV）" },
      { name: "面包车" },
      { name: "中型客车" },
      { name: "大型客车" },
      { name: "轻型载货汽车" },
      { name: "中型载货汽车" },
      { name: "重型载货汽车" },
      { name: "越野汽车（SUV）" },
      { name: "农用运输车" },
      { name: "牵引汽车" },
      { name: "挂车" },
      { name: "农用机械" },
      { name: "摩托车" },
      { name: "电瓶摩托车" },
    ],
  },
  fuelType: {
    isShow: false,
    title: "燃油类别",
    list: [
      { name: "汽油" },
      { name: "柴油" },
      { name: "油气" },
      { name: "纯电" },
      { name: "油电" },
      { name: "无动力" },
      { name: "天然气" },
    ],
  },
  material: {
    isShow: false,
    title: "钢圈材质",
    list: [{ name: "铝质" }, { name: "铁质" }],
  },
});

const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "vehicleType") {
    model1.formData.vehicleType = v.name;
  } else if (key === "fuelType") {
    model1.formData.fuelType = v.name;
  } else if (key === "material") {
    model1.formData.wheelMaterial = v.name;
  }
};
// 授权
const handleUpload = () => {
  upload()
  // uni.authorize({
  //   // #ifdef MP-TOUTIAO
  //   scope: "scope.album, scope.writePhotosAlbum,scope.camera",
  //   // #endif
  //   success(res) {
  //     console.log("检测权限通过", res);
  //   },
  //   fail(err) {
  //     console.log("检测权限不通过", err);
  //     uni.hideLoading();
  //   },
  // });
  // uni.authorize({
  //   scope: "scope.writePhotosAlbum",
  //   success() {
  //     console.log("授权成功");
  //     // 用户同意授权后，可以执行相关上传文件的操作
  //   },
  //   fail() {
  //     console.log("用户拒绝授权");
  //     // 引导用户到设置中开启权限
  //     if (uni.getSystemInfoSync().platform === "android") {
  //       uni.showModal({
  //         title: "提示",
  //         content: "此功能需要访问您的相册，请在设置中允许访问相册",
  //         success: function (modalRes) {
  //           if (modalRes.confirm) {
  //             uni.openSetting();
  //           }
  //         },
  //       });
  //     }
  //   },
  // });
};
// 上传
const upload = () => {
  uni.chooseImage({
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths;
      PictureApi.upload({
        files: tempFilePaths[0],
        path: tempFilePaths[0],
      }).then((res: any) => {
        if (res.code === 200) {
          model1.formData.licensePhotoUrl = res.data.url;
          const ocr = JSON.parse(res.data.ocr);
          if (ocr.error_code) {
            uni.showToast({
              icon: "none",
              title: "未识别出相关信息",
            });
            model1.formData.licensePhotoUrl = "";
            model1.formData.ascription = "";
            model1.formData.licenseNumber = "";
            model1.formData.vin = "";
            model1.formData.brandModel = "";
          } else {
            model1.formData.ascription = ocr.words_result["所有人"].words;
            model1.formData.licenseNumber = ocr.words_result["号牌号码"].words;
            model1.formData.vin = ocr.words_result["车辆识别代号"].words;
            model1.formData.brandModel = ocr.words_result["品牌型号"].words;
          }
        }
      });
    },
    fail: (error) => {
      console.log(error);
    },
  });
};

/**
 * 校验
 */
const form = ref();
const check = () => {
  return new Promise((resolve) => {
    form.value
      .validate()
      .then((res: boolean) => {
        resolve(res);
      })
      .catch((errors: any) => {
        resolve(false);
        uni.showToast({
          icon: "none",
          title: errors[0].message || "校验失败",
        });
      });
  });
};

const save = () => {
  check().then((res) => {
    if (res) {
      startSave();
    }
  });
  // if (store.profile?.token) {
  //   check().then((res) => {
  //     if (res) {
  //       startSave();
  //     }
  //   });
  // } else {
  //   uni.login({
  //     provider: "toutiao",
  //     success: function (loginRes) {
  //       UserApi.login({ code: loginRes.code }).then((res: any) => {
  //         if (res.data) {
  //           store.setProfile({ token: res.data.token });
  //           check().then((res) => {
  //             if (res) {
  //               startSave();
  //             }
  //           });
  //         } else {
  //           uni.showToast({ title: "授权失败", icon: "none" });
  //         }
  //       });
  //     },
  //   });
  // }
};

const startSave = () => {
  VehicleApi.add(model1.formData).then((res) => {
    if (res.code === 200) {
      uni.showToast({
        title: "提交成功",
      });
      uni.navigateBack();
    }
  });
};
</script>
<style lang="scss" scoped>
::v-deep .uni-card__content {
  padding: 20rpx !important;
  height: calc(100vh - 100px);
  overflow: auto;
}
::v-deep .uni-card--shadow {
  padding: 0px !important;
}
::v-deep .u-form-item {
  height: auto;
  border-bottom: 1rpx solid rgba(233, 233, 233, 0.76);
  margin: 0px 20rpx;
  padding: 0px 20rpx;
}
.title {
  font-weight: 500;
  font-size: 32rpx;
  color: #000000;
}
.btn-box-fix-btn {
  justify-content: center;
  view {
    width: 70%;
  }
}
</style>
