<template>
  <view class="content">
    <uni-nav-bar left-icon="back" @clickLeft="back" statusBar fixed title="添加客户"></uni-nav-bar>
    <view>
      <view class="qn-form-item qn-form-item__title">
        <text class="title">基础信息</text>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">企业名称</text>
        </view>
        <view class="value">
          <qn-easyinput :maxlength="20" @blur="showCompany" v-model="form.name" :inputBorder="false" text="right" placeholder="请输入企业名称"></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <text class="label__text">企业简称</text>
        </view>
        <view class="value">
          <qn-easyinput :maxlength="20" v-model="form.shortName" :inputBorder="false" text="right" placeholder="请输入企业简称"></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <text class="label__text">联系人</text>
        </view>
        <view class="value">
          <qn-easyinput :maxlength="20" v-model="form.contactName" :inputBorder="false" text="right" placeholder="请输入用户名称"></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <text class="label__text">联系手机</text>
        </view>
        <view class="value">
          <qn-easyinput
            :maxlength="11"
            type="number"
            v-model="form.contactMobile"
            :inputBorder="false"
            text="right"
            placeholder="请输入用户手机号"
          ></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <text class="label__text">担任职务</text>
        </view>
        <view class="value">
          <qn-easyinput :maxlength="20" v-model="form.contactTitle" :inputBorder="false" text="right" placeholder="请输入用户职务"></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item__title">
        <text class="title">工商信息</text>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">信用代码</text>
        </view>
        <view class="value">
          <qn-easyinput
            :maxlength="18"
            :disabled="hasSelected"
            :styles="{ disableColor: '#fff' }"
            v-model="form.uniformSocialCreditCode"
            :inputBorder="false"
            text="right"
            placeholder="请输入信用代码"
          ></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">所在区域</text>
        </view>
        <view class="value">
          <!-- <qn-easyinput v-model="form.shortName" :inputBorder="false" text="right" placeholder="选择所在区域"></qn-easyinput> -->
          <qn-data-picker
            :readonly="hasSelected"
            text="right"
            :border="false"
            class="qn-picker"
            placeholder="区域"
            popup-title="请选择城市"
            :map="{ text: 'name', value: 'id' }"
            @change="onAreaChange"
            :clear-icon="true"
            :localdata="items"
          >
            <text v-if="form.locDistrictId">
              {{ `${form.locProvinceName || ''}/${form.locCityName || ''}/${form.locDistrictName || ''}/${form.locStreetName || ''}` }}
            </text>
          </qn-data-picker>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">详细地址</text>
        </view>
        <view class="value">
          <qn-easyinput
            :maxlength="20"
            :disabled="hasSelected"
            :styles="{ disableColor: '#fff' }"
            v-model="form.locDetail"
            :inputBorder="false"
            text="right"
            placeholder="请输入详细地址"
          ></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">法人/实控人</text>
        </view>
        <view class="value">
          <qn-easyinput
            :maxlength="20"
            :disabled="hasSelected"
            :styles="{ disableColor: '#fff' }"
            v-model="form.legalPersonName"
            :inputBorder="false"
            text="right"
            placeholder="请输入法人/实控人"
          ></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">法人/实控人手机</text>
        </view>
        <view class="value">
          <qn-easyinput
            :maxlength="11"
            type="number"
            :disabled="hasSelected"
            :styles="{ disableColor: '#fff' }"
            v-model="form.legalPersonMobile"
            :inputBorder="false"
            text="right"
            placeholder="请输入法人/实控人手机"
          ></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">法人/实控人身份证号</text>
        </view>
        <view class="value">
          <qn-easyinput
            :maxlength="18"
            :disabled="hasSelected"
            :styles="{ disableColor: '#fff' }"
            v-model="form.legalPersonIdCardNo"
            :inputBorder="false"
            text="right"
            placeholder="请输入身份证号"
          ></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item" style="flex-wrap: wrap">
        <view class="label" style="margin-top: 18rpx">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">身份证照片</text>
        </view>
        <view class="value">
          <view class="upload-area">
            <image class="idCard" @click="!hasSelected && selectedImage('legalPersonIdCardFrontImg')" :src="frontIDCard" />
            <image class="idCard" @click="!hasSelected && selectedImage('legalPersonIdCardBackImg')" :src="backIDCard" />
          </view>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">营业执照</text>
        </view>
        <view class="value">
          <text
            v-if="!form.businessLicenseImg"
            @click="!hasSelected && selectedImage('businessLicenseImg')"
            :style="`font-size: 28rpx; color: ${hasSelected ? '#eee' : '#007aff'}`"
          >
            点击上传
          </text>
          <text
            v-if="form.businessLicenseImg"
            @click="!hasSelected && selectedImage('businessLicenseImg')"
            :style="`font-size: 28rpx;margin-right: 16rpx; color: ${hasSelected ? '#eee' : '#007aff'}`"
          >
            重新上传
          </text>
          <text v-if="form.businessLicenseImg" @click="!hasSelected && showImage()" style="font-size: 28rpx; color: #007aff">预览</text>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">注册资本(万)</text>
        </view>
        <view class="value">
          <qn-easyinput
            type="digit"
            maxlength="10"
            :disabled="hasSelected"
            :styles="{ disableColor: '#fff' }"
            v-model="form.registeredCapital"
            :inputBorder="false"
            text="right"
            placeholder="请输入注册资本"
          ></qn-easyinput>
        </view>
      </view>
      <view class="qn-form-item qn-form-item">
        <view class="label">
          <uni-icons custom-prefix="iconfont" type="icon-required" size="14" color="#F5222D"></uni-icons>
          <text class="label__text">成立日期</text>
        </view>
        <view class="value">
          <qn-datetime-picker v-model="form.foundDate" type="date" :border="false" :disabled="hasSelected"></qn-datetime-picker>
          <!-- <qn-easyinput v-model="form.registeredCapital" :inputBorder="false" text="right" placeholder="请输入成立时间"></qn-easyinput> -->
        </view>
      </view>
    </view>
    <uni-popup ref="popup" type="bottom">
      <view class="popup_modal">
        <slot name="title">
          <view class="popup_modal-title">可选择已录入公司</view>
        </slot>
        <scroll-view scroll-y="true" class="popup_modal-scroll">
          <view @click="selectCompany(item.enterpriseId)" class="popup_modal-scroll-item" v-for="item in searchList" :key="item.enterpriseId">
            {{ item.enterpriseName }}
          </view>
        </scroll-view>
      </view>
    </uni-popup>
    <qn-footer fixed height="120rpx">
      <view class="button-area">
        <view class="button button__cancel" @click="back">
          <text class="text">取消</text>
        </view>
        <view class="button button__submit" @click="addUser">
          <text class="text" style="color: white">添加客户</text>
        </view>
      </view>
    </qn-footer>
  </view>
</template>

<script>
import { back, uploadImage } from '@/utils/hook.js'
import { getArea } from '@/apis/commonApi.js'
import { getCompanyList, getCompanyInfoById, addCustomer } from '@/apis/addUserApi.js'
import qnEasyinput from '@/components/qn-easyinput/qn-easyinput.vue'
import qnDataPicker from '@/components/qn-data-picker/qn-data-picker.vue'
import qnDatetimePicker from '@/components/qn-datetime-picker/qn-datetime-picker.vue'
import qnFooter from '@/components/qn-footer/qn-footer.vue'
const validateFields = [
  'name',
  'uniformSocialCreditCode',
  'legalPersonName',
  'locProvinceId',
  'locCityId',
  'locDistrictId',
  'locStreetId',
  'locProvinceName',
  'locCityName',
  'locDistrictName',
  'locStreetName',
  'locDetail',
  'legalPersonIdCardNo',
  'legalPersonIdCardFrontImg',
  'legalPersonIdCardBackImg',
  'businessLicenseImg',
  'registeredCapital',
  'foundDate'
]
export default {
  components: { qnEasyinput, qnDataPicker, qnDatetimePicker, qnFooter },
  data() {
    return {
      form: {
        id: null,
        name: null,
        shortName: null,
        contactName: null,
        contactMobile: null,
        contactTitle: null,
        uniformSocialCreditCode: null,
        locProvinceId: null,
        locCityId: null,
        locDistrictId: null,
        locStreetId: null,
        locProvinceName: null,
        locCityName: null,
        locDistrictName: null,
        locStreetName: null,
        locDetail: null,
        legalPersonName: null,
        legalPersonMobile: null,
        legalPersonIdCardNo: null,
        legalPersonIdCardFrontImg: null,
        legalPersonIdCardBackImg: null,
        businessLicenseImg: null,
        registeredCapital: null,
        foundDate: null
      },
      searchList: [],
      hasSelected: false,
      items: []
    }
  },
  mounted() {
    getArea().then((res) => {
      if (res) {
        this.items = res
      }
    })
  },
  methods: {
    back,
    showCompany(e) {
      let enterpriseName = e.detail.value.trim()
      if (enterpriseName) {
        getCompanyList({ enterpriseName }).then((res) => {
          if (res) {
            this.searchList = res.records
            if (this.searchList.length > 0) {
              this.$refs.popup.open('bottom')
            }
          }
        })
      }
    },
    selectCompany(enterpriseId) {
      this.$refs.popup.close()
      getCompanyInfoById({ enterpriseId }).then((res) => {
        if (res) {
          this.form.id = enterpriseId
          this.form.name = res.name
          // 信息反显
          this.reflectiveCompany(res)
          setTimeout(() => {
            this.hasSelected = true
          }, 0)
        }
      })
    },
    reflectiveCompany(info) {
      this.form.uniformSocialCreditCode = info.uniformSocialCreditCode
      this.form.locProvinceId = info.locProvinceId
      this.form.locCityId = info.locCityId
      this.form.locStreetId = info.locStreetId
      this.form.locDistrictId = info.locDistrictId
      this.form.locProvinceName = info.locProvinceName
      this.form.locCityName = info.locCityName
      this.form.locStreetName = info.locStreetName
      this.form.locDistrictName = info.locDistrictName
      this.form.locDetail = info.locDetail
      this.form.registeredCapital = info.registeredCapital
      this.form.foundDate = info.foundDate
    },
    onAreaChange(e) {
      if (e.detail.value && e.detail.value.length > 0) {
        const [province, city, district, street] = e.detail.value
        this.form.locProvinceId = province.value
        this.form.locProvinceName = province.text
        this.form.locCityId = city.value
        this.form.locCityName = city.text
        this.form.locDistrictId = district.value
        this.form.locDistrictName = district.text
        this.form.locStreetId = street.value
        this.form.locStreetName = street.text
      } else {
        this.form.locProvinceId = null
        this.form.locProvinceName = null
        this.form.locCityId = null
        this.form.locCityName = null
        this.form.locDistrictId = null
        this.form.locDistrictName = null
        this.form.locStreetId = null
        this.form.locStreetName = null
      }
    },
    selectedImage(type) {
      uploadImage()
        .then((urls) => {
          if (urls) {
            this.form[type] = urls[0]
          }
        })
        .catch((e) => {
          uni.showToast({
            title: '上传失败',
            icon: 'fail'
          })
        })
    },
    showImage() {
      uni.previewImage({
        urls: [this.form.businessLicenseImg]
      })
    },
    addUser() {
      if (!this.form.id) {
        for (let i = 0; i < validateFields.length; i++) {
          if (this.form[validateFields[i]] === null || this.form[validateFields[i]] === '') {
            uni.showToast({
              title: '请完善信息',
              icon: 'none'
            })
            return
          }
        }
        if (!/^1[3456789]\d{9}$/.test(this.form['legalPersonMobile'])) {
          uni.showToast({
            title: '请输入正确法人手机号',
            icon: 'none'
          })
          return
        }
        // if (!/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/.test(this.form['legalPersonIdCardNo'])) {
        //   uni.showToast({
        //     title: '请输入正确法人身份证号',
        //     icon: 'none'
        //   })
        //   return
        // }
      }
      if (this.form.contactMobile && !/^1[3456789]\d{9}$/.test(this.form['contactMobile'])) {
        uni.showToast({
          title: '请输入正确联系人手机号',
          icon: 'none'
        })
        return
      }
      addCustomer(this.form).then((res) => {
        if (res) {
          uni.showToast({
            title: '添加成功',
            icon: 'success'
          })
          setTimeout(() => {
            back()
          }, 1000)
        }
      })
    }
  },
  watch: {
    ['form.name'](val) {
      if (this.hasSelected) {
        console.log('watch:', val)
        this.hasSelected = false
        this.form.id = null
        this.reflectiveCompany({})
      }
    }
  },
  computed: {
    frontIDCard() {
      let url = 'https://qncloud.oss-cn-shenzhen.aliyuncs.com/paper_shopkeeper/frontIDCard.png'
      if (this.hasSelected || !this.form.legalPersonIdCardFrontImg) {
        return url
      }
      return this.form.legalPersonIdCardFrontImg
    },
    backIDCard() {
      let url = 'https://qncloud.oss-cn-shenzhen.aliyuncs.com/paper_shopkeeper/backDCard.png'
      if (this.hasSelected || !this.form.legalPersonIdCardBackImg) {
        return url
      }
      return this.form.legalPersonIdCardBackImg
    }
  }
}
</script>

<style lang="scss">
.content {
  width: 750rpx;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}
.qn-form-item {
  width: 750rpx;
  padding: 0rpx 32rpx;
  background-color: #fff;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  border-bottom: 2rpx solid #d8d8d8;
  min-height: 80rpx;
  .label {
    flex-grow: 0;
    flex-shrink: 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    margin-right: 20rpx;
    .label__text {
      font-size: 28rpx;
      color: #000000;
    }
  }
  .value {
    flex-grow: 1;
    flex-shrink: 1;
    text-align: right;
  }
}
.qn-form-item__title {
  background-color: #f7f8fa;
  padding: 20rpx 32rpx;
  border: none;
  .title {
    font-size: 30rpx;
    color: #888888;
  }
}
.popup_modal {
  width: 750rpx;
  height: 600rpx;
  background-color: #fff;
  border-radius: 10px 10px 0 0;
  .popup_modal-title {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 750rpx;
    height: 88rpx;
    font-weight: 600;
    border-bottom: 2rpx solid #d8d8d8;
  }
  .popup_modal-scroll {
    width: 750rpx;
    height: 600rpx;
    .popup_modal-scroll-item {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;
      width: 750rpx;
      height: 88rpx;
      padding: 0rpx 32rpx;
      border-bottom: 2rpx solid #d8d8d8;
    }
  }
}
.upload-area {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-top: 10rpx;
  margin-bottom: 24rpx;
  .idCard {
    width: 324rpx;
    height: 280rpx;
    flex-grow: 0;
    flex-shrink: 0;
  }
}
.button-area {
  width: 750rpx;
  padding: 0 32rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .button {
    flex-grow: 0;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10rpx;
    .text {
      font-size: 30rpx;
      font-weight: 500;
      text-align: center;
    }
  }
  .button__cancel {
    width: 270rpx;
    height: 88rpx;
    border: 2rpx solid #979797;
  }
  .button__submit {
    width: 400rpx;
    height: 88rpx;
    background: #007aff;
  }
}
</style>
