<template>
  <div class="JPattributeEditor">
    <van-nav-bar class="navBar" title="金牌店档案编辑" left-arrow @click-left="onClickLeft" />
    <div class="content" v-if="detail">
      <van-form ref="tabstoreVal">
        <van-field
          class="sendCode"
          v-model="detail.ownerMobile"
          label="主经营者电话"
          placeholder="请输入主经营者电话"
          @blur="sendCodeTelFn(detail.ownerMobile)"
          type="tel">
          <template #button v-if="!verifyMobile">
            <van-button
              size="small"
              style="color: white; background: rgb(0, 87, 186); border-radius: 6px"
              @click="sendCode(detail.ownerMobile)"
              :disabled="telConfirm">
              <span v-if="telConfirm">已确认</span>
              <span v-else>确认真实</span>
            </van-button>
          </template>
        </van-field>
        <span style="color: #ee0a24;font-size: 12px;">为了不打扰金牌店老板，不再发送短信验证码，请务必确认手机号正确无误!</span>
        <!-- <van-field
          v-model="verificationVal"
          label="主经营者收到的验证码"
          placeholder="请输入验证码"
          type="number"
          @blur="verification(verificationVal)"
          v-if="!verifyMobile" /> -->
        <van-field v-model="detail.ownerName" :error-message="ownerNameMsg" label="主经营者姓名" />
        <!-- <van-field
          v-model="detail.ownerBirthday"
          label="主经营者出生日期"
          placeholder="请输入主经营者出生日期"
          @click="getNyr('ownerBirthday', detail.ownerBirthday)" /> -->
        <van-field autosize type="textarea" label="主营/擅长经营品类">
          <template #input>
            <van-checkbox-group v-model="detail.mainProductCategorys" direction="horizontal">
              <van-checkbox
                v-for="(item, index) in mainProductCategorys"
                :name="item.dictValue"
                shape="square"
                :key="index">
                {{ item.dictValue }}
              </van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>
        <van-field
          v-model="detail.totalSalesAmount"
          type="number"
          :error-message="totalSalesAmountMsg"
          label="门店24年总进货额(含所有品牌品类，单位:万元)" />
        <van-field
          v-model="detail.performanceRatio"
          type="number"
          :error-message="performanceRatioMsg"
          label="门店立邦业绩占比(单位:%)" />
        <van-field
          v-model="detail.mainBrand"
          autosize
          type="textarea"
          :error-message="mainBrandMsg"
          label="门店主营TOP3品牌" />
        <van-field label="是否有工地资源（支持工地配送，承接工地双包等）">
          <template #input>
            <van-radio-group
              v-model="detail.constructionResource"
              direction="horizontal"
              @change="changeResource">
              <van-radio name="是">是</van-radio>
              <van-radio name="否">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-if="detail.constructionResource == '是'"
          v-model="detail.constructionYearNum"
          type="number"
          :error-message="constructionYearNumMsg"
          label="年工地数量" />
        <van-field label="是否有双包能力">
          <template #input>
            <van-radio-group v-model="detail.doubleContracting" direction="horizontal">
              <van-radio name="是">是</van-radio>
              <van-radio name="否">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field label="紧急联系人身份">
          <template #input>
            <van-radio-group v-model="detail.emergencyContactRelation" direction="horizontal">
              <van-radio
                v-for="(item, index) in emergencyContactRelation"
                :name="item.dictValue"
                :key="index">
                {{ item.dictValue }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field v-model="detail.emergencyContact" label="紧急联系人姓名" />
        <!-- <van-field
          v-model="detail.emergencyContactBirthday"
          label="紧急联系人出生日期"
          @click="getNyr('emergencyContactBirthday', detail.emergencyContactBirthday)" /> -->
        <van-field
          v-model="detail.emergencyContactMobile"
          type="number"
          @blur="emergencyContactBlur(detail.emergencyContactMobile)"
          label="紧急联系人电话" />
      </van-form>
    </div>
    <div class="footer-btn">
      <van-button
        style="color: white; background: rgb(0, 87, 186); border-radius: 6px; width: 90%"
        @click="confirmShare">
        保 存
      </van-button>
    </div>
    <!-- 时间选择 -->
    <van-popup v-model="datetimeShowPicker" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="datetimeOnConfirm"
        @cancel="datetimeShowPicker = false" />
    </van-popup>
  </div>
</template>

<script>
import { sendAndCheckVerCode, getDictOption } from '@/api/index';
import { getStoreArchives, updateArchives } from '@/api/storeManagement';
export default {
  name: 'JPattributeEditor',
  data() {
    return {
      ownerNameMsg: '',
      totalSalesAmountMsg: '',
      performanceRatioMsg: '',
      mainBrandMsg: '',
      constructionYearNumMsg: '',
      detail: null,
      time: null, //计时
      timeNum: 60,
      verificationVal: '',
      datetimeShowPicker: false,
      activatNyrItem: '',
      checkboxGroup: [],
      mainProductCategorys: [],
      emergencyContactRelation: [],
      verificationPassedPhoneNum: '', //验证通过手机号
      minDate: new Date(1945, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(1945, 0, 1),
      mobileStatus: '0',
      verifyMobile: false, //手机号是否验证透通过
      telConfirm: false,
    };
  },
  activated() {
    this.telConfirm = false;
    this.ownerNameMsg = '';
    this.totalSalesAmountMsg = '';
    this.performanceRatioMsg = '';
    this.mainBrandMsg = '';
    this.constructionYearNumMsg = '';
    this.detail = null;
    this.verificationVal = '';
    if (this.time) clearInterval(this.time);
    this.time = null; //计时
    this.timeNum = 60;
    this.toastLoading(0, '加载中...', true);
    getDictOption({}, 'archives_main_product_categorys').then((res) => {
      let mainProductCategorys = [];
      let emergencyContactRelation = [];
      res.data.forEach((val) => {
        if (val.remark == 'mainProductCategorys') {
          mainProductCategorys.push(val);
        } else {
          emergencyContactRelation.push(val);
        }
      });
      this.mainProductCategorys = mainProductCategorys;
      this.emergencyContactRelation = emergencyContactRelation;
      this.getDetaild();
    });
  },
  methods: {
    getDetaild() {
      getStoreArchives({ storeCode: this.$route.query.storeCode }).then((res) => {
        this.toastLoading().clear();
        if (res.code == 200) {
          //   let copyData = JSON.parse(JSON.stringify(res.data));
          res.data.mainProductCategorys = res.data.mainProductCategorys
            ? res.data.mainProductCategorys.split(',')
            : [];
          this.detail = res.data;
          this.mobileStatus = res.data.mobileStatus;
          // mobileStatus  是否验证通过 1，2是
          if (res.data.mobileStatus == '1' || res.data.mobileStatus == '2') {
            this.verificationPassedPhoneNum = this.detail.ownerMobile;
          }
          // 验证码和发送按钮是否显示
          this.verifyMobile = this.mobileStatus == '0' ? false : true;
        }
      });
    },
    sendCodeTelFn(tel) {
      if (!/^1[123456789]\d{9}$/.test(tel) || tel == '') {
        this.$toast('格式错误');
        return;
      }
      if (tel != this.verificationPassedPhoneNum) {
        this.telConfirm = false;
        this.verifyMobile = false;
      } else {
        this.telConfirm = false;
        this.verifyMobile = true;
      }
    },
    // 发送验证码
    sendCode(val) {
      if (!/^1[123456789]\d{9}$/.test(val) || val == '') {
        this.$toast('格式错误');
        return;
      }
      this.telConfirm = true;
      this.verificationPassedPhoneNum = val;
      this.$toast('验证成功');
      // if (this.time) return;
      // clearInterval(this.time);
      // this.timeNum = 60;
      // this.sendCodeFun(
      //   {
      //     type: '1', //String	调用类型：1：发送验证码 2：校验验证码
      //     phone: val, //String	手机号
      //     verification: '', //String	手机号验证码
      //   },
      //   () => {
      //     this.time = setInterval(() => {
      //       this.timeNum--;
      //       if (this.timeNum <= 0) {
      //         clearInterval(this.time);
      //         this.time = null;
      //       }
      //     }, 1000);
      //     this.$toast('发送成功');
      //   }
      // );
    },
    sendCodeFun(params, callback) {
      sendAndCheckVerCode(params).then((res) => {
        if (res.code == 200) {
          callback && callback(res);
        }
      });
    },
    verification(val) {
      // 验证码
      if (val == '') {
        return;
      }
      // 手机号
      if (this.detail.ownerMobile == '') {
        return;
      }
      this.sendCodeFun(
        {
          type: '2', //String	调用类型：1：发送验证码 2：校验验证码
          phone: this.detail.ownerMobile, //String	手机号
          verification: val, //String	手机号验证码
        },
        (res) => {
          if (res.data) this.verificationPassedPhoneNum = this.detail.ownerMobile;
          this.$toast(res.data ? '验证成功' : '验证码错误');
        }
      );
    },
    getNyr(val, date) {
      this.activatNyrItem = val;
      if (date && date != '') {
        let time = date.split('-');
        this.currentDate = new Date(time[0], Number(time[1]) - 1, time[2]);
      } else {
        this.currentDate = new Date(1945, 0, 1);
      }
      this.datetimeShowPicker = true;
    },
    datetimeOnConfirm(time) {
      this.$set(this.detail, this.activatNyrItem, this.parseTime(time, '{y}-{m}-{d}'));
      //   this.detail.ownerBirthday = this.parseTime(time, '{y}-{m}-{d}');
      this.datetimeShowPicker = false;
    },
    isValidOwnerName() {
      this.ownerNameMsg = '';
      let ownerName = this.detail.ownerName;
      if (ownerName.length < 2) {
        this.ownerNameMsg = '最短字数2';
        return true;
      }
      if (ownerName.length > 20) {
        this.ownerNameMsg = '最长字数20';
        return true;
      }
      const chineseChars = ownerName.match(/[\u4e00-\u9fa5]/g) || [];
      if (chineseChars.length < 1) {
        this.ownerNameMsg = '至少一个汉字';
        return true;
      }
      if (!/^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]*)*·?$/.test(ownerName)) {
          this.ownerNameMsg = '只能输入中文';
          return true;
      }
      // if (!/^[\u4e00-\u9fa5a-zA-Z0-9·]+$/.test(ownerName)) {
      //   this.ownerNameMsg = '不可输入特殊符号';
      //   return true;
      // }
      return false;
    },
    isValidTotalSalesAmount() {
      this.totalSalesAmountMsg = '';
      let totalSalesAmount = this.detail.totalSalesAmount;
      const value = parseFloat(totalSalesAmount);
      if (isNaN(value)) {
        this.totalSalesAmountMsg = '请输入数字';
        return true;
      }
      if (value < 1) {
        this.totalSalesAmountMsg = '最小值1';
        return true;
      }
      if (value > 1000) {
        this.totalSalesAmountMsg = '最大值1000';
        return true;
      }
      return false;
    },

    isConstructionYearNum() {
      this.constructionYearNumMsg = '';
      let constructionYearNum = this.detail.constructionYearNum;
      const value = parseFloat(constructionYearNum);
      if (isNaN(value)) {
        this.constructionYearNumMsg = '请输入数字';
        return true;
      }
      if (value < 1) {
        this.constructionYearNumMsg = '最小值1';
        return true;
      }
      if (value > 10000) {
        this.constructionYearNumMsg = '最大值10000';
        return true;
      }
      return false;
    },
    isPerformanceRatio() {
      this.performanceRatioMsg = '';
      let performanceRatio = this.detail.performanceRatio;
      const value = parseFloat(performanceRatio);
      if (isNaN(value)) {
        this.performanceRatioMsg = '请输入数字';
        return true;
      }
      if (value < 1) {
        this.performanceRatioMsg = '最小值1';
        return true;
      }
      if (value > 100) {
        this.performanceRatioMsg = '最大值100';
        return true;
      }
      return false;
    },
    isValidMainBrand() {
      this.mainBrandMsg = '';
      let mainBrand = this.detail.mainBrand;
      const chineseChars = mainBrand.match(/[\u4e00-\u9fa5]/g) || [];
      if (chineseChars.length < 1) {
        this.mainBrandMsg = '至少一个汉字';
        return true;
      }
      return false;
    },
    // 保存
    confirmShare() {
      if (
        this.verificationPassedPhoneNum == '' ||
        this.detail.ownerMobile != this.verificationPassedPhoneNum
      ) {
        this.$toast('请验证手机号');
        return;
      }
      this.isValidOwnerName();
      this.isValidTotalSalesAmount();
      this.isPerformanceRatio();
      this.isValidMainBrand();
      if (this.detail.constructionResource == '是') {
        this.isConstructionYearNum();
      }
      if (this.isValidOwnerName()) return;
      if (this.isValidTotalSalesAmount()) return;
      if (this.isPerformanceRatio()) return;
      if (this.isValidMainBrand()) return;
      if (this.detail.constructionResource == '是') {
        if (this.isConstructionYearNum()) return;
      }
      if (this.detail.emergencyContactMobile != '') {
        if (!/^1[123456789]\d{9}$/.test(this.detail.emergencyContactMobile)) {
          this.$toast('紧急联系人电话格式错误');
          return;
        }
      }
      this.toastLoading(0, '加载中...', true);
      let params = JSON.parse(JSON.stringify(this.detail));
      params.mainProductCategorys = params.mainProductCategorys.join(',');
      params.storeCode = this.$route.query.storeCode;
      updateArchives(params).then((res) => {
        this.toastLoading().clear();
        if (res.code == 200) {
          this.$toast(res.msg);
          this.$router.go(-1);
        } else {
          this.$toast(res.msg);
        }
      });
    },
    emergencyContactBlur(val) {
      if (!/^1[123456789]\d{9}$/.test(val)) {
        this.$toast('紧急联系人电话格式错误');
      }
    },
    changeResource(val) {
      if (val == '否') {
        this.detail.constructionYearNum = '';
      }
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="scss">
.JPattributeEditor {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  overflow: hidden;
  .content {
    flex: 1;
    overflow-y: auto;
    background: #fff;
    padding: 10px 15px;
    margin-top: 10px;
    background: #fff;
    .van-cell {
      padding: 10px 0;
      border-bottom: 1px solid #ccc;
    }
    .van-field__label {
      width: 9em;
    }
    .sendCode {
      border: none !important;
      input {
        border: 1px solid #f1f1f1;
        height: 35px;
      }
    }
    .van-checkbox--horizontal {
      margin-bottom: 10px;
      width: 100%;
    }
    .van-radio--horizontal {
      margin-bottom: 10px;
    }
  }
  .footer-btn {
    display: flex;
    justify-content: space-around;
    padding: 10px 0;
  }
}
</style>
