<template>
  <uni-card
    :shadow="'0rpx 0rpx 10rpx 0rpx rgba(5,68,37,0.12)'"
    :margin="'20px'"
    :border="false"
  >
    <view class="uni-card__content">
      <u-form
        labelPosition="left"
        :model="model1"
        :rules="rules"
        ref="form"
        :labelWidth="80"
        :labelStyle="{ padding: '0rpx 10rpx' }"
        :errorType="'border-bottom'"
      >
        <!-- <view class="title">车辆信息</view>
        <view v-for="(item, index) in formAttrList" :key="index">
          <u-form-item
            v-if="item.name !== '行驶证'"
            :prop="`formData.${item.key}`"
            :label="item.name"
            :required="item.required"
            @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>
            <template #right v-if="item.type === 'select'">
              <u-icon name="arrow-right" @click="item.fn"></u-icon>
            </template>
          </u-form-item>
          <view v-else-if="item.name === '行驶证'">
            <view style="padding: 22rpx">
              <text
                style="color: #f56c6c; font-size: 20px; margin-right: 5px"
              ></text>
              <text style="color: #303133; font-size: 15px; line-height: 22px"
                >行驶证</text
              >（拍照上传后自动识别车辆信息）</view
            >
            <view style="display: flex; justify-content: space-around">
              <view>
                <view style="padding-left: 20rpx; margin-top: 20rpx">
                  <image
                    @click="handleUpload(1)"
                    :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>

              <view>
                <view style="padding-left: 20rpx; margin-top: 20rpx">
                  <image
                    @click="handleUpload(2)"
                    :src="
                      model1.formData.licenseBackUrl ||
                      `${url}/static/img/vehicle/upload.png`
                    "
                    style="width: 203rpx; height: 133rpx"
                  />
                </view>
                <view style="padding-left: 20rpx; margin-top: 10rpx"
                  >点击上传行驶证副页</view
                >
              </view>
            </view>
          </view>
        </view> -->

        <view class="title">登记信息</view>

        <u-form-item
          :prop="`formData.${item.key}`"
          :label="item.name"
          :required="item.required"
          v-for="(item, index) in formAttrList1"
          :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"
            :disabledColor="'#ffffff'"
            :type="['contactInfo'].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>
          <template #right v-if="item.type === 'select'">
            <u-icon name="arrow-right" @click="item.fn"></u-icon>
          </template>
        </u-form-item>

        <view class="title mt-30">我要选新车</view>

        <u-form-item
          :prop="`formData.${item.key}`"
          :label="item.name"
          :required="item.required"
          v-for="(item, index) in formAttrList2"
          :key="index"
          @click="item.fn"
        >
          <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>
          <template #right v-if="item.type === 'select'">
            <u-icon name="arrow-right" @click="item.fn"></u-icon>
          </template>
        </u-form-item>
      </u-form>
    </view>
  </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
      .concat(formAttrList1)
      .concat(formAttrList2)"
    :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>

  <!-- 车牌号 -->
  <CarNoDialog
    :show="showDialog.showCarNo"
    @handleDialog="(v:boolean) => {handleDialog('showCarNo', v)}"
    @changeCarNo="changeCarNo"
    ref="carNoRef"
  ></CarNoDialog>

  <!-- 供应商选择弹框 -->
  <BrandDialog
    ref="BrandDialog"
    :show="showDialog.showBrand"
    @handleDialog="(v:boolean) => {handleDialog('showBrand', v)}"
    @handleChange="handleChange"
  ></BrandDialog>

  <!-- <u-picker
    :show="contrlModalParams['location'].isShow"
    :title="contrlModalParams['location'].title"
    ref="uPicker"
    :columns="contrlModalParams['location'].list"
    @cancel="contrlModalParams['location'].isShow = false"
    keyName="cityName"
    @confirm="confirm"
  ></u-picker> -->
  <ccSelectDity
    :province="contrlModalParams['location'].province"
    :city="contrlModalParams['location'].city"
    :area="contrlModalParams['location'].area"
    :show="contrlModalParams['location'].isShow"
    @changeClick="changeClick"
    @sureSelectArea="onsetCity"
    @hideShow="onhideShow"
  ></ccSelectDity>
</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);
import CarNoDialog from "@/components/Dialog/CarNoDialog.vue";
import BrandDialog from "@/components/Dialog/BrandDialog.vue";
import ccSelectDity from "@/components/cc-selectDity/cc-selectDity.vue";
import { onLoad } from "@dcloudio/uni-app";
const model1 = reactive<any>({
  formData: {},
});
const formAttrList = reactive<any>([
  {
    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: true,
    unit: "",
  },
  {
    name: "品牌型号",
    key: "brandModel",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "系列",
    key: "series",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "总重量",
    key: "totalWeight",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "车牌号",
    key: "licensePlate",
    type: "input",
    required: true,
    unit: "",
    disabled: true,
    fn: () => {
      uni.hideKeyboard();
      showDialog.showCarNo = true;
    },
  },
]);

const formAttrList1 = reactive<any>([
  {
    name: "车辆所属",
    key: "ownerType",
    type: "select",
    childKey: "ownerType",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams["ownerType"].isShow = true;
    },
  },
  {
    name: "联系人",
    key: "owner_name",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "联系方式",
    key: "owner_phone",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "所在地",
    key: "location",
    type: "input",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams.location.isShow = true;
      contrlModalParams.location.title = "所在地";
    },
  },
  {
    name: "详细地址",
    key: "address",
    type: "input",
    required: true,
    unit: "",
  },
]);

const formAttrList2 = reactive<any>([
  {
    name: "选择品牌",
    key: "brandName",
    type: "select",
    required: false,
    unit: "",
    fn: () => {
      uni.hideKeyboard();
      showDialog.showBrand = true;
    },
  },
  {
    name: "预算范围",
    key: "budgetRange",
    type: "select",
    childKey: "budgetRange",
    required: false,
    unit: "",
    fn: () => {
      contrlModalParams["budgetRange"].isShow = true;
    },
  },
]);
const rules = reactive({
  "formData.owner_name": {
    type: "string",
    required: true,
    message: "请输入姓名",
    trigger: ["blur", "change"],
  },
  "formData.owner_phone": {
    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"],
  // },
  // "formData.vin": {
  //   type: "string",
  //   required: true,
  //   message: "请输入车架号",
  //   trigger: ["blur", "change"],
  // },
  // "formData.brandModel": {
  //   type: "string",
  //   required: true,
  //   message: "请输入品牌型号",
  //   trigger: ["blur", "change"],
  // },
  // "formData.series": {
  //   type: "string",
  //   required: true,
  //   message: "请输入系列",
  //   trigger: ["blur", "change"],
  // },
  // "formData.totalWeight": {
  //   type: "string",
  //   required: true,
  //   message: "请输入总重量",
  //   trigger: ["blur", "change"],
  // },
  // "formData.licensePlate": {
  //   type: "string",
  //   required: true,
  //   message: "请输入车牌号",
  //   trigger: ["blur", "change"],
  // },

  "formData.ownerType": {
    type: "string",
    required: true,
    message: "请选择车辆所属",
    trigger: ["blur", "change"],
  },
  "formData.location": {
    type: "string",
    required: true,
    message: "请选择省市区",
    trigger: ["blur", "change"],
  },
  "formData.address": {
    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: "铁质" }],
  },
  ownerType: {
    isShow: false,
    title: "车辆所属",
    list: [{ name: "个人" }, { name: "单位" }],
  },
  budgetRange: {
    isShow: false,
    title: "预算范围",
    list: [
      { name: "10万以下" },
      { name: "10-15万" },
      { name: "15-20万" },
      { name: "20-25万" },
      { name: "25-30万" },
      { name: "30-40万" },
      { name: "40-50万" },
      { name: "50万以上" },
    ],
  },
  location: {
    isShow: false,
    title: "所在地",
    list: [],
    province: "广东省",
    city: "广州市",
    area: "天河区",
    areaCode: "440106",
    address: "",
  },
});

// 供应商选择
const showDialog = <any>reactive({
  showCarNo: false,
  showBrand: false,
});

const handleDialog = (key: string, v: boolean) => {
  showDialog[key] = v;
};

const changeCarNo = (plate: string) => {
  if (plate.length >= 7) model1.formData.licensePlate = plate;
  showDialog.showCarNo = false;
};

const handleChange = (arr: any) => {
  model1.formData.brandName = arr
    .map((item: any) => {
      return item.brandName;
    })
    .toString();
  model1.formData.brandId = arr
    .map((item: any) => {
      return item.id;
    })
    .toString();
};

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;
  } else if (key === "ownerType") {
    model1.formData.ownerType = v.name;
  } else if (key === "budgetRange") {
    model1.formData.budgetRange = v.name;
  }
};

// const confirm = (e: any) => {
//   if (e.value[1]) {
//     // model1.formData.shmCategoryId = e.value[1].id;
//     // model1.formData.location = e.value[1].shmCategoryName;
//     contrlModalParams["location"].isShow = false;
//   }
// };
// 授权
const handleUpload = (type: number) => {
  if (type === 1) {
    uploadFront();
  } else if (type === 2) {
    uploadBack();
  }

  // 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 uploadFront = () => {
  uni.chooseImage({
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths;
      PictureApi.upload({
        files: tempFilePaths[0],
        path: tempFilePaths[0],
        front: true,
      }).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.licensePlate = "";
            model1.formData.vin = "";
            model1.formData.brandModel = "";
          } else {
            model1.formData.ascription = ocr.words_result["所有人"].words;
            model1.formData.licensePlate = ocr.words_result["号牌号码"].words;
            model1.formData.vin = ocr.words_result["车辆识别代号"].words;
            model1.formData.brandModel = ocr.words_result["品牌型号"].words;
          }
        }
      });
    },
    fail: (error) => {
      console.log(error);
    },
  });
};

const uploadBack = () => {
  uni.chooseImage({
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths;
      PictureApi.upload({
        files: tempFilePaths[0],
        path: tempFilePaths[0],
        front: false,
      }).then((res: any) => {
        if (res.code === 200) {
          // console.log(res);
          model1.formData.licenseBackUrl = res.data.url;
          const ocr = JSON.parse(res.data.ocr);
          if (ocr.error_code) {
            uni.showToast({
              icon: "none",
              title: "未识别出相关信息",
            });
          } else {
            const curbWeight = ocr.words_result["整备质量"].words;
            const totalWeight = ocr.words_result["总质量"].words;
            model1.formData.curbWeight = curbWeight.slice(
              0,
              curbWeight.length - 2
            );
            model1.formData.totalWeight = totalWeight.slice(
              0,
              totalWeight.length - 2
            );
            model1.formData.fuelType = ocr.words_result["燃油类型"].words;
            model1.formData.licensePlate = 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.updateRegis({
    ...model1.formData,
    ownerType: model1.formData.ownerType === "个人",
    status: 2,
  }).then((res) => {
    if (res.code === 200) {
      uni.showToast({
        title: "提交成功",
      });
      uni.navigateBack();
    }
  });
};

const handleBack = () => {
  uni.navigateBack();
};

const getLocationList = () => {
  VehicleApi.getLocation({}).then((res: any) => {
    if (res.code === 200) {
      contrlModalParams.location.list = res.data[0].children;
      // console.log(contrlModalParams.location.list);
      // contrlModalParams.reCategory.list = [
      //   (res.data as any).map((item: any) => {
      //     return { ...item, name: item.reCategoryName };
      //   }),
      // ];
      // contrlModalParams.reCategory.list.push(
      //   contrlModalParams.reCategory.list[0][0].childrenList
      // );
    }
  });
};

function changeClick(value, value2, value3, value4) {
  // console.log("地址选择器 = " + value + value2 + value3 + value4);

  contrlModalParams["location"].province = value;
  contrlModalParams["location"].city = value2;
  contrlModalParams["location"].area = value3;
  contrlModalParams["location"].areaCode = value4;
}
function onhideShow() {
  contrlModalParams["location"].isShow = false;
  // console.log("执行了关闭地址选择器");
}
//选中省市区
function onsetCity(e) {
  let data = e.detail.target.dataset;
  let address = data.province + data.city + data.area;
  contrlModalParams["location"].isShow = false;
  contrlModalParams["location"].address = address;
  model1.formData.location = address;
}

onMounted(() => {
  getLocationList();
});

onLoad((option: any) => {
  // 接收传递的标题参数
  if (option.id) {
    model1.formData.id = option.id;
    VehicleApi.getDetail({ id: option.id }).then((res: any) => {
      if (res.code === 200) {
        model1.formData = {
          ...res.data,
          ownerType: res.data.ownerType ? "单位" : "个人",
        };
      }
    });
  }
});
</script>
<style lang="scss" scoped>
.uni-card__content {
  padding: 10px !important;
  height: calc(100vh - 100px);
  overflow: auto;
}
::v-deep .uni-card--shadow {
  padding: 0px !important;
}
::v-deep .u-form-item {
  height: auto !important;
  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%;
  }
}

.price {
  font-size: 38rpx;
  font-weight: bold;
  color: red;
  text-align: center;
}
.tip {
  font-size: 22rpx;
  color: rgba(0, 0, 0, 0.35);
  margin-top: 20rpx;
  text-align: center;
}
</style>
