<!-- @format -->

<template>
  <view class="container">
    <view style="color: #3c9cff" class="informationTitle"
      >填写被授权人信息</view
    >

    <view class="cardImage">
      <view class="updateContent">
        <view style="margin: 0 auto">
          <u-upload
            name="1"
            :fileList="fileList1"
            @afterRead="afterRead"
            @delete="deletePic"
            :maxCount="1"
            width="280"
            height="180"
          >
            <view class="uploadTipcContent">
              <view class="cardImg">
                <image
                  style="height: 180rpx; width: 400rpx"
                  mode="widthFix"
                  :src="require('@/static/images/cardzm.png')"
                ></image>
                <view class="topic"> 请上传被授权人身份证人像照片 </view>
              </view>
            </view>
            <!-- <view class="uploadTipcContent">
              <view>
                <view style="display: flex; justify-content: center">
                  <u-icon
                    name="arrow-upward"
                    color="#2979ff"
                    size="28"
                  ></u-icon>
                </view>
                <u-button
                  :customStyle="{ color: '#3c9cff', fontSize: '26rpx' }"
                  type="text"
                  size="small"
                  >点击上传</u-button
                >
              </view>
              <view class="topic"> 请上传被授权人身份证正面照片 </view>
            </view> -->
          </u-upload>
        </view>
      </view>

      <view class="updateContent">
        <view style="margin: 0 auto">
          <u-upload
            name="2"
            :fileList="fileList2"
            @afterRead="afterRead"
            @delete="deletePic"
            :maxCount="1"
            width="280"
            height="180"
          >
            <view class="uploadTipcContent">
              <view class="cardImg">
                <image
                  style="height: 180rpx; width: 430rpx; margin-left: 30rpx"
                  mode="widthFix"
                  :src="require('@/static/images/cardbm.png')"
                ></image>
                <view class="topic"> 请上传被授权人身份证国徽照片 </view>
              </view>
            </view>
          </u-upload>
        </view>
      </view>
    </view>

    <view class="informationContent">
      <view class="contentItems">
        <u-form ref="uForm" labelWidth="150" :model="form" labelPosition="top">
          <view class="content">
            <u-form-item
              :required="true"
              style="border-bottom: 1px solid rgb(242, 242, 242)"
              label="被委托人身份证号码:"
              prop="idNum"
            >
              <u-input
                placeholder="请输入被委托人身份证号码"
                @blur="handleUpadteSync('idNum')"
                v-model="form.idNum"
              ></u-input>
            </u-form-item>
          </view>
          <view class="content">
            <u-form-item
              :required="true"
              style="border-bottom: 1px solid rgb(242, 242, 242)"
              label="被委托人姓名:"
              prop="name"
            >
              <u-input
                placeholder="请输入被委托人姓名"
                @blur="handleUpadteSync('name')"
                v-model="form.name"
              ></u-input>
            </u-form-item>
          </view>

          <view class="content">
            <u-form-item
              :required="true"
              style="border-bottom: 1px solid rgb(242, 242, 242)"
              label="识别结果:"
            >
              <view>
                <span v-if="isNextDisbaled" style="color: #ff9900"
                  >识别结果不符，请前往电脑端注册。</span
                >
                <span v-else style="color: #19be6b"
                  >被委托人姓名与法定代表/负责人一致</span
                >
              </view>
            </u-form-item>
          </view>

          <view class="content">
            <u-form-item
              :required="true"
              style="border-bottom: 1px solid rgb(242, 242, 242)"
              label="用户名:"
              prop="type"
            >
              <u-input
                disabled
                :value="formdData.companiesOrcResult.regNum"
              ></u-input>
            </u-form-item>
          </view>

          <view class="content">
            <u-form-item
              :required="true"
              style="border-bottom: 1px solid rgb(242, 242, 242)"
              label="单位联系电话:"
              prop="landline"
            >
              <u-input
                @input="handleLandline"
                v-model="form.landline"
                placeholder="请输入联系电话"
              ></u-input>
            </u-form-item>
          </view>

          <view class="content">
            <u-form-item
              :required="true"
              style="border-bottom: 1px solid rgb(242, 242, 242)"
              label="联系人手机号:"
              prop="userMobile"
            >
              <u-input
                @input="handleUserMobile"
                v-model="form.userMobile"
                placeholder="请输入联系人手机号"
              ></u-input>
            </u-form-item>
          </view>
        </u-form>
      </view>
    </view>
  </view>
</template>

<script>
import { idcardOCR } from "@/api/companiesRegistered";

export default {
  data() {
    return {
      showModal: false,
      fileList1: [],
      fileList2: [],
      form: {
        landline: "",
        userMobile: "",
        idNum: "",
        name: "",
      },

      rules: {
        idNum: [
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.idCard(value);
            },
            message: "身份证号不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
          {
            required: true,
            message: "被委托人身份证号码不能为空",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "被授权人姓名不能为空",
            trigger: "blur",
          },
        ],
        landline: [
          {
            required: true,
            message: "单位联系电话不能为空",
            trigger: "blur",
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              return uni.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
        userMobile: [
          {
            required: true,
            message: "联系人手机号不能为空",
            trigger: "blur",
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              return uni.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  props: {
    formdData: {
      type: Object,
      default: () => ({}),
    },
    authorizerRef: {},
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules);
    this.$emit("update:authorizerRef", this.$refs.uForm);
  },
  computed: {
    isNextDisbaled() {
      if (
        this.formdData.personCardOrcResult.name &&
        this.formdData.companiesOrcResult.person
      ) {
        return (
          this.formdData.personCardOrcResult.name !==
          this.formdData.companiesOrcResult.person
        );
      } else {
        return false;
      }
    },
  },
  created() {
    if (this.formdData.personCardOrcResult.cardFrontImg) {
      this.fileList1[0] = {
        url: this.$baseUrl + this.formdData.personCardOrcResult.cardFrontImg,
      };
      this.fileList2[0] = {
        url: this.$baseUrl + this.formdData.personCardOrcResult.cardBackImg,
      };
    }

    Object.keys(this.form).forEach((key) => {
      this.form[key] = this.formdData.personCardOrcResult[key];
    });
  },
  methods: {
    handleUpadteSync(key) {
      this.$emit("update:formdData", {
        ...this.formdData,
        personCardOrcResult: {
          ...this.formdData.personCardOrcResult,
          [key]: this.form[key],
        },
      });
    },
    handleLandline() {
      this.$emit(
        "update:formdData",
        Object.assign({
          ...this.formdData,
          personCardOrcResult: {
            ...this.formdData.personCardOrcResult,
            landline: this.form.landline,
          },
        })
      );
    },
    handleUserMobile() {
      this.$emit(
        "update:formdData",
        Object.assign({
          ...this.formdData,
          personCardOrcResult: {
            ...this.formdData.personCardOrcResult,
            userMobile: this.form.userMobile,
          },
        })
      );
    },
    //处理身份证ocr识别
    async handleCardOrc() {
      uni.showLoading({
        title: "智能识别中...",
      });
      try {
        let {
          data: { idcardDownOcrResult, idcardUpOcrResult },
        } = await idcardOCR([this.fileList1[0].url, this.fileList2[0].url]);

        this.$emit(
          "update:formdData",
          Object.assign({
            ...this.formdData,
            personCardOrcResult: {
              name: idcardUpOcrResult.name,
              idNum: idcardUpOcrResult.idNum,
              cardFrontImg: this.fileList1[0].url,
              cardBackImg: this.fileList2[0].url,
            },
          })
        );

        this.form.name = idcardUpOcrResult.name;
        this.form.idNum = idcardUpOcrResult.idNum;
        setTimeout(() => {
          uni.hideLoading();
          console.log(this.formdData);
        }, 2000);
      } catch (error) {
        uni.showLoading({
          title: "识别错误",
        });
        setTimeout(() => {
          uni.hideLoading();
        }, 2000);
      } finally {
      }
    },
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: JSON.parse(result.data).fileName,
          })
        );
        fileListLen++;
      }
      this.fileList1.length && this.fileList2.length && this.handleCardOrc();
    },

    //上传
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: `${this.$baseUrl}/api/common/upload`, // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          success: (res) => {
            setTimeout(() => {
              resolve(res);
            }, 1000);
          },
        });
      });
    },
  },
};
</script>

<style lang="scss">
.cardImg {
  width: 100%;
  display: flex;
  justify-content: center;
}
.topic {
  color: #909399;
  font-size: 24rpx;
  width: 400rpx;
  margin: 20rpx auto 0;
  font-family: "宋体";
  position: absolute;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-43%);
}
.uploadTipcContent {
  width: 600rpx;
  height: 260rpx;
  position: relative;
  // padding: 30rpx;

  // border: 1px dotted#909399;
}
.updateContent {
  display: flex;
  background: #fff;
  padding: 30rpx;
}
.informationTitle {
  margin-bottom: 30rpx;
  font-size: 30;
}

.contentItems {
  width: 100%;
  border-radius: 6px;
  background: #fff;
  margin: 0rpx auto 30rpx;
  padding: 20rpx 30rpx 20rpx;

  .content {
    border-bottom: 1px solid rgb(242, 242, 242);
  }

  .content:last-child {
    border-bottom: none;
  }

  .title {
    font-size: 30rpx;
    color: black;
    letter-spacing: 3rpx;
  }

  .message {
    margin-left: 70rpx;
    text-align: left;
    // width: 420rpx;
    font-size: 30rpx;
    color: rgb(146, 146, 146);
    // white-space: nowrap;
    // /* 禁止文本换行 */
    // overflow: hidden;
    // /* 隐藏超出容器的文本 */
    // text-overflow: ellipsis;
    /* 使用省略号表示被截断的文本 */
  }
}
</style>
