<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 === 'textarea'"
          v-model="(model1.formData as any)[item.key]"
          :placeholder="`请输入${item.name}`"
          clearable
          :customStyle="{}"
          border="none"
          :disabled="item.disabled"
        >
          <template #suffix>
            <text v-if="item.unit">
              {{ item.unit }}
            </text>
          </template>
        </u-input>

        <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'].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 style="padding-left: 20rpx; margin-top: 20rpx">
            <image
              @click="handleUpload"
              v-if="model1.formData.photoUrl"
              :src="model1.formData.photoUrl"
              mode="widthFix"
              style="width: 100%;"
            />
            <image
              v-else
              @click="handleUpload"
              :src="`${url}/static/img/battery/upload.png`"
              style="width: 48rpx; height: 37rpx"
            />
          </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>


  <u-datetime-picker
      :show="contrlModalParams.isShowTime"
      v-model="contrlModalParams.time"
      mode="date"
      @confirm="(v: any) => {handleTime(v)}"
      @cancel="contrlModalParams.isShowTime = false"
      :closeOnClickOverlay="true"
      @close="contrlModalParams.isShowTime = false"
    ></u-datetime-picker>

  <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, BatteryApi, UserApi } from "@/services";
import {
  formatDate
} from "@/utils";
import pinia from "@/store";
import { useMemberStore } from "@/store/index";
const store = useMemberStore(pinia);
const model1 = reactive<any>({
  formData: {
    preferredVisitTime: formatDate(new Date(), "{y}-{m}-{d}"),
  },
});
const formAttrList = reactive<any>([
  {
    name: "姓名",
    key: "name",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "联系方式",
    key: "contactInfo",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "联系地址",
    key: "contactAddress",
    type: "input",
    required: true,
    unit: "",
  },
  {
    name: "期望上门时间",
    key: "preferredVisitTime",
    type: "input",
    required: true,
    unit: "",
    disabled: true,
    fn: () => {
      uni.hideKeyboard()
      contrlModalParams.isShowTime = true;
    },
  },
  {
    name: "回收种类",
    key: "recyclingType",
    type: "select",
    childKey: "recyclingType",
    required: true,
    unit: "",
    fn: () => {
      contrlModalParams["recyclingType"].isShow = true;
    },
  },

  {
    name: "回收重量",
    key: "recyclingWeight",
    type: "input",
    required: true,
    unit: "KG",
  },
  {
    name: "上传照片",
    key: "photoUrl",
    type: "upload",
    required: false,
    unit: "",
  },
  {
    name: "备注",
    key: "remarks",
    type: "textarea",
    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.contactAddress": {
    type: "string",
    required: true,
    message: "请输入联系地址",
    trigger: ["blur", "change"],
  },
  "formData.preferredVisitTime": {
    type: "string",
    required: true,
    message: "请输入期望上门时间",
    trigger: ["blur", "change"],
  },
  "formData.recyclingType": {
    type: "string",
    required: true,
    message: "请选择回收种类",
    trigger: ["blur", "change"],
  },
  "formData.recyclingWeight": {
    type: "string",
    required: true,
    message: "请输入回收重量",
    trigger: ["blur", "change"],
  },
  // "formData.photoUrl": {
  //   type: "string",
  //   required: true,
  //   message: "请上传照片",
  //   trigger: ["blur", "change"],
  // },
});

const contrlModalParams = reactive<any>({
  isShowTime: false,
  time: formatDate(new Date(), "{y}-{m}-{d}"),
  recyclingType: {
    isShow: false,
    title: "车辆类型",
    list: [
      { name: "锂电池包" },
      { name: "锂电模组" },
      { name: "电芯" },
      { name: "极片" },
    ],
  },
});

const handleSelect = (key: string, v: any) => {
  contrlModalParams[key].isShow = false;
  if (key === "recyclingType") {
    model1.formData.recyclingType = v.name;
  }
};
// 授权
const handleUpload = () => {
  upload();
  // uni.getSetting({success(res){
  //   if(!res.authSetting['scope.userInfo']) {
  //     uni.showModal({
  //       title:'提示',
  //       content:'授权后继续操作',
  //       showCancel:false,
  //       confirmText:'同意',
  //       cancelText:'',
  //       success:(res)=>{
  //         if(res.confirm) {
  //           uni.openSetting({success: res => {
  //             debugger
  //             if(res.authSetting['scope.userInfo']) {
  //               upload()
  //             }
  //           }})
  //         }
  //       },
  //     })
  //   }
  // }})
};
// 上传
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.photoUrl = res.data.url;
        }
      });
    },
    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 = () => {
  BatteryApi.addRegis(model1.formData).then((res) => {
    if (res.code === 200) {
      uni.showToast({
        title: "提交成功",
      });
      uni.navigateBack();
    }
  });
};

const handleTime = (v: any) => {
  model1.formData.preferredVisitTime = formatDate(v.value, "{y}-{m}-{d}");
  contrlModalParams.isShowTime = false;
};
</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>
