<template>
  <view class="content">
    <uni-nav-bar left-icon="back" @clickLeft="back" statusBar fixed title="授信记录"></uni-nav-bar>
    <view class="form">
      <view class="justify-between group">
        <view class="flex-row">
          <text class="text_1">*</text>
          <text class="text_2">营业执照</text>
        </view>
        <text v-show="!form.businessLicenseImg" class="text_3" @click="selectImg('businessLicenseImg')">点击上传</text>
        <view v-show="form.businessLicenseImg" class="flex-row">
          <text class="text_3" @click="preview(form.businessLicenseImg)">预览</text>
          <text v-if="operation == 'add'" class="text_3" style="color: #f5222d; margin-left: 16rpx" @click="selectImg('businessLicenseImg')">重新上传</text>
        </view>
      </view>
      <view class="divider"></view>
      <view class="justify-between group">
        <view class="flex-row">
          <text class="text_1">*</text>
          <text class="text_2">联系人</text>
        </view>
        <qn-easyinput
          :maxlength="10"
          v-model="form.contactName"
          :inputBorder="false"
          text="right"
          placeholderStyle="fontSize: 28rpx"
          placeholder="请输入联系人"
        ></qn-easyinput>
      </view>
      <view class="divider"></view>
      <view class="justify-between group">
        <view class="flex-row">
          <text class="text_1">*</text>
          <text class="text_2">联系手机</text>
        </view>
        <qn-easyinput
          :maxlength="11"
          v-model="form.contactMobile"
          :inputBorder="false"
          text="right"
          type="number"
          placeholderStyle=" fontSize: 28rpx"
          placeholder="请输入联系人手机号"
        ></qn-easyinput>
      </view>
      <view class="divider"></view>
      <view class="justify-between group">
        <view class="flex-row">
          <text class="text_1">*</text>
          <text class="text_2">工厂地址</text>
        </view>
        <qn-data-picker
          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.locDistrictName">
            {{ `${form.locProvinceName || ''}/${form.locCityName || ''}/${form.locDistrictName || ''}/${form.locStreetName || ''}` }}
          </text>
        </qn-data-picker>
      </view>
      <view class="divider"></view>
      <view class="justify-between group">
        <view class="flex-row">
          <text class="text_1">*</text>
          <text class="text_2">详细地址</text>
        </view>
        <qn-easyinput
          :maxlength="20"
          v-model="form.locDetail"
          :inputBorder="false"
          text="right"
          placeholderStyle=" fontSize: 28rpx"
          placeholder="请输入详细地址"
        ></qn-easyinput>
      </view>
      <view class="divider"></view>
      <view class="flex-col group_9">
        <view class="flex-row group_10">
          <text class="text_18">*</text>
          <text class="text_19">工厂图片</text>
        </view>
        <view class="flex-row">
          <view v-for="(url, index) in imgList" :key="url" class="image-area">
            <image class="image__close-icon" @click="clearImage(index)" src="/static/imgs/general/close-icon.png"></image>
            <image :src="url" class="upload_image" @click="preview(url)"></image>
          </view>
          <view v-show="imgList.length < 5" class="flex-col items-center section_4" @click="selectImg('factory')">
            <image src="/static/imgs/general/camera-icon.png" class="image_6" />
            <text class="text_20">点击上传</text>
          </view>
        </view>
      </view>
      <view class="flex-col group_9">
        <view class="flex-row group_10">
          <text class="text_19">工厂视频(可选)</text>
        </view>
        <view class="video-area" v-if="video.fileUrl">
          <video :src="video.fileUrl" class="video"></video>
          <cover-image class="video__close-icon" @click="clearVideo" src="/static/imgs/general/close-icon.png"></cover-image>
        </view>
        <view v-show="!video.fileUrl" class="flex-col items-center section_4" @click="selectVideo">
          <image src="/static/imgs/general/camera-icon.png" class="image_6" />
          <text class="text_20">点击上传</text>
        </view>
      </view>
      <view class="group">
        <view class="flex-row">
          <text class="text_1">*</text>
          <text class="text_2">工厂介绍</text>
        </view>
        <qn-easyinput
          :maxlength="200"
          v-model="form.factoryIntroduce"
          type="textarea"
          placeholderStyle="fontSize: 28rpx "
          placeholder="请输入工厂介绍"
          style="background-color: rgb(247, 248, 250); margin-top: 16rpx"
        ></qn-easyinput>
      </view>
    </view>
    <qn-footer fixed>
      <view class="flex-col items-center text-wrapper_1" @click="save">
        <text>保存</text>
      </view>
    </qn-footer>
  </view>
</template>

<script>
import { go2, back } from '@/utils/hook.js'
export default {
  data() {
    return {
      id: null,
      operation: 'add'
    }
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id
      this.operation = 'edit'
    }
  },
  methods: {
    go2,
    back
  }
}
</script>

<script>
import { getArea, getLicenseOcr } from '@/apis/commonApi.js'
import { uploadImage, uploadVideo, back } from '@/utils/hook.js'
import { validateField } from '@/utils/index.js'
import { fileType } from '@/enums/index.js'
import { getFactoryInfo, saveFactoryInfo } from '@/apis/factoryApi.js'

const validateFields = [
  {
    name: 'businessLicenseImg',
    rules: [{ required: true, message: '请上传营业执照' }]
  },
  {
    name: 'contactName',
    rules: [{ required: true, message: '请输入联系人' }]
  },
  {
    name: 'contactMobile',
    rules: [
      { required: true, message: '请输入联系人手机号' },
      { type: 'phone', message: '请输入正确的手机号' }
    ]
  },
  {
    name: 'locProvinceName',
    rules: [{ required: true, message: '请选择省份' }]
  },
  {
    name: 'imgItemList',
    rules: [{ required: true, message: '请上传工厂图片' }]
  },
  {
    name: 'locCityName',
    rules: [{ required: true, message: '请选择城市' }]
  },
  {
    name: 'locDistrictName',
    rules: [{ required: true, message: '请选择区域' }]
  },
  {
    name: 'locDetail',
    rules: [{ required: true, message: '请输入详细地址' }]
  },
  {
    name: 'factoryIntroduce',
    rules: [{ required: true, message: '请输入工厂介绍' }]
  }
]

export default {
  data() {
    return {
      id: null,
      form: {
        businessLicenseImg: '',
        uniformSocialCreditCode: '',
        name: '',
        contactName: '',
        contactMobile: '',
        locDetail: '',
        factoryIntroduce: '',
        imgItemList: [],
        locProvinceName: '',
        locProvinceId: '',
        locCityName: '',
        locCityId: '',
        locDistrictName: '',
        locDistrictId: '',
        locStreetName: '',
        locStreetId: ''
      },
      items: [],
      imgList: [],
      video: {
        fileUrl: null,
        videoPicUrl: null
      },
      operation: 'add'
    }
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id
      this.operation = 'edit'
    }
  },
  created() {
    if (this.id) {
      getFactoryInfo({ id: this.id }).then((res) => {
        if (res) {
          this.operation = 'edit'
          for (let key in this.form) {
            this.form[key] = res[key]
          }
          this.form.id = res.id
          // 解析图片
          this.form.imgItemList = []
          this.imgList = res.imgItemList.filter((item) => item.type == fileType.IMG).map((item) => item.fileUrl)
          let video = res.imgItemList.find((item) => item.type == fileType.VIDEO)
          if (video) {
            this.video.fileUrl = video.fileUrl
            this.video.videoPicUrl = video.videoPicUrl
          }
        }
      })
    }
  },
  mounted() {
    getArea().then((res) => {
      if (res) {
        this.items = res
      }
    })
  },
  watch: {
    imgList(val) {
      this.form.imgItemList = val.map((url) => ({
        fileUrl: url,
        type: fileType.IMG
      }))
    }
  },
  methods: {
    back,
    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
      }
    },
    // 校验
    validate() {
      for (let field of validateFields) {
        const { name, rules } = field
        const value = this.form[name]
        const { isValid, msg } = validateField(value, rules)
        if (!isValid) {
          uni.showToast({
            title: msg,
            icon: 'none'
          })
          return false
        }
      }
      // 将视频路径写入imgItemList
      if (this.video.fileUrl) {
        this.form.imgItemList.push({
          type: fileType.VIDEO,
          fileUrl: this.video.fileUrl,
          videoPicUrl: this.video.videoPicUrl
        })
      }
      return this.form
    },
    selectImg(type) {
      let count = 1
      if (type == 'factory') {
        count = 5 - this.imgList.length
      }
      uploadImage(undefined, count)
        .then((urls) => {
          if (urls) {
            // 营业执照OCR
            if (type == 'businessLicenseImg') {
              this.licenseOcr(urls[0])
            }
            if (type == 'factory') {
              this.imgList.push(...urls)
            }
          }
        })
        .catch((e) => {
          uni.showToast({
            title: '上传失败:' + (e.message || e),
            icon: 'fail',
            duration: 1500
          })
        })
    },
    selectVideo() {
      uploadVideo()
        .then((video) => {
          if (video) {
            this.video.fileUrl = video.url
            this.video.videoPicUrl = video.thumb
          }
        })
        .catch((e) => {
          uni.showToast({
            title: '上传失败:' + (e.message || JSON.stringify(e)),
            icon: 'fail'
          })
        })
    },
    clearVideo() {
      this.video = {
        fileUrl: null,
        videoPicUrl: null
      }
    },
    clearImage(index) {
      this.imgList.splice(index, 1)
    },
    // 营业执照OCR
    licenseOcr(url) {
      getLicenseOcr({ photoUrl: url }).then((res) => {
        if (res) {
          if (!res.regNum) {
            uni.showToast({
              title: '识别社会信用代码失败',
              icon: 'none'
            })
            return
          }
          if (!res.company) {
            uni.showToast({
              title: '识别企业名称失败',
              icon: 'none'
            })
            return
          }
          this.form.uniformSocialCreditCode = res.regNum
          this.form.name = res.company
          this.form.businessLicenseImg = url
        }
      })
    },
    preview(url) {
      uni.previewImage({
        urls: [url],
        current: url
      })
    },
    save() {
      const form = this.validate()
      if (form) {
        saveFactoryInfo(form).then((res) => {
          back()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  width: 750rpx;
}
.form {
  width: 750rpx;
  background-color: #fff;
}
.group {
  padding: 24rpx 28rpx 24rpx 32rpx;
  font-size: 28rpx;
  line-height: 40rpx;
  white-space: nowrap;
  .text_3 {
    color: rgb(0, 122, 255);
  }
  .text_1 {
    color: rgb(245, 34, 45);
  }
  .text_2 {
    margin-left: 4rpx;
    color: rgb(0, 0, 0);
  }
}
.divider {
  margin: 0 28rpx;
  background-color: rgb(216, 216, 216);
  height: 2rpx;
}
.group_9 {
  margin: 22rpx 28rpx 0;
  padding: 0 4rpx 31rpx;
  border-bottom: solid 2rpx rgb(216, 216, 216);
  .group_10 {
    padding-bottom: 16rpx;
    .text_18 {
      color: rgb(245, 34, 45);
      font-size: 28rpx;
      line-height: 40rpx;
      white-space: nowrap;
    }
    .text_19 {
      margin-left: 4rpx;
      color: rgb(0, 0, 0);
      font-size: 28rpx;
      line-height: 40rpx;
      white-space: nowrap;
    }
  }
  .section_4 {
    margin-left: 19rpx;
    padding: 23rpx 0 13rpx;
    color: rgb(76, 74, 88);
    font-size: 26rpx;
    line-height: 37rpx;
    white-space: nowrap;
    background-color: rgba(220, 222, 224, 0.5);
    border-radius: 10rpx;
    width: 120rpx;
    .image_6 {
      width: 42rpx;
      height: 36rpx;
    }
    .text_20 {
      margin-top: 12rpx;
    }
  }
}
.upload_image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 10rpx;
}
.video-area {
  position: relative;
  width: 686rpx;
  .video__close-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 32rpx;
    height: 32rpx;
    z-index: 100;
  }
  .video {
    width: 686rpx;
    height: 450rpx;
  }
}
.image-area {
  position: relative;
  margin-left: 19rpx;
  width: 120rpx;
  height: 120rpx;
  border-radius: 10rpx;

  .image__close-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 32rpx;
    height: 32rpx;
    z-index: 1;
  }
}
.text-wrapper_1 {
  margin: 0 32rpx;
  padding: 23rpx 0;
  background-color: rgb(0, 122, 255);
  border-radius: 10rpx;
  color: rgb(255, 255, 255);
}
</style>
