<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"
          :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 formAttrList1"
        :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>
  </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)" :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>
</template>

<script setup lang="ts">
import CarNoDialog from "@/components/Dialog/CarNoDialog.vue";
import BrandDialog from "@/components/Dialog/BrandDialog.vue";
import { VehicleApi, UserApi } from "@/services";
import pinia from "@/store";
import { useMemberStore } from "@/store/index";
const store = useMemberStore(pinia);
// 供应商选择
const showDialog = <any>reactive({
  showCarNo: false,
  showBrand: false
});
const model1 = reactive<any>({
  formData: {},
});
const formAttrList = reactive<any>([
  {
    name: "车辆所属",
    key: "ownerType",
    type: "select",
    childKey: "ownerType",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams["ownerType"].isShow = true;
    },
  },
  {
    name: "联系方式",
    key: "contactInfo",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "车牌号",
    key: "licensePlate",
    type: "input",
    required: true,
    unit: "",
    disabled: true,
    fn: () => {
      uni.hideKeyboard();
      showDialog.showCarNo = true;
    },
  },
  {
    name: "所在地",
    key: "location",
    type: "input",
    required: true,
    unit: "",
  },
]);

const formAttrList1 = 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.ownerType": {
    type: "string",
    required: true,
    message: "请选择车辆所属",
    trigger: ["blur", "change"],
  },
  "formData.contactInfo": {
    type: "string",
    required: true,
    message: "请输入联系方式",
    trigger: ["blur", "change"],
  },
  "formData.licensePlate": {
    type: "string",
    required: true,
    message: "请输入车牌号",
    trigger: ["blur", "change"],
  },
  "formData.location": {
    type: "string",
    required: true,
    message: "请输入所在地",
    trigger: ["blur", "change"],
  },
});

const contrlModalParams = reactive<any>({
  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万以上" },
    ],
  },
});

const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "ownerType") {
    model1.formData.ownerType = v.name;
  } else if(key === 'budgetRange') {
    model1.formData.budgetRange = v.name;
  }
};

/**
 * 校验
 */
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) => {

  //     });
  //   },
  // });
  // }
};

const startSave = () => {
  VehicleApi.addRegis({
    ...model1.formData,
    ownerType: model1.formData.ownerType === "个人" ? 0 : 1,
  }).then((res) => {
    if (res.code === 200) {
      uni.showToast({
        title: "提交成功",
      });
      uni.navigateBack();
    }
  });
};

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()
};
</script>
<style lang="scss" scoped>
::v-deep .uni-card__content {
  padding: 20rpx !important;
  height: calc(100vh - 200px);
  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>
