<template>
  <view class="view">
    <view class="block">
      <view style="">
        <text style="color: #f8285a; margin-right: 4px">*</text>
        企业名称
      </view>
      <view class="value">
        <uni-easyinput
          type="text"
          placeholder="请输入企业名称"
          :inputBorder="false"
          style="text-align: center"
          :value="form.enterprisesName"
          @blur="proofName"
          :clearable="false"
          :autoHeight="true"
          :adjust-position="true"
          cursorSpacing="32"
          ref="nameRef"
        ></uni-easyinput>
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>

    <view class="block">
      <view style="">
        <text style="color: #f8285a; margin-right: 4px">*</text>
        企业地址
      </view>
      <view class="value" @tap="chooseAddress">
        <input
          class="input-value"
          type="text"
          placeholder-class="txt"
          placeholder="请选择企业地址"
          v-model="form.address"
          disabled
        />
        <u-icon name="map"></u-icon>
      </view>
    </view>

    <view class="block">
      <view style="">
        <text style="color: #f8285a; margin-right: 4px">*</text>
        企业介绍
      </view>
      <view class="value" @tap="goIntruduce">
        <view class="input-textarea" v-if="form.introduction">
          {{ form.introduction }}
        </view>
        <view class="input-textarea" style="color: #808080" v-else>
          请输入企业介绍
        </view>
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>

    <view class="upload-wrapper">
      <view
        class="wd-flex"
        style="
          justify-content: space-between;
          align-items: center;
          width: 100%;
        "
      >
        <view style="">
          <text style="color: #f8285a; margin-right: 4px">*</text>
          企业照片
        </view>
        <view style="color: #808080">最多可传3张</view>
      </view>
      <u-upload
        :fileList="form.photo"
        @afterRead="addEnterprisePhoto"
        @delete="delEnterprisePhoto"
        multiple
        :maxCount="3"
        width="101"
        height="101"
      ></u-upload>
    </view>

    <view class="block">
      <view class="label">
        <text style="color: #f8285a; margin-right: 4px">*</text>
        企业标签
      </view>
      <view class="value" style="width: 50%" @tap="goTags">
        <view class="input-value" v-if="Object.keys(form.tags).length">
          {{
            Object.values(form.tags)
              .map(tag => tag.name)
              .join('、')
          }}
        </view>
        <view class="input-textarea" style="color: #808080" v-else>
          请选择企业标签
        </view>
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>

    <view class="block">
      <view style="">
        <text style="color: #f8285a; margin-right: 4px">*</text>
        企业负责人
      </view>
      <view class="value">
        <uni-easyinput
          type="text"
          placeholder="请输入企业负责人"
          :inputBorder="false"
          v-model="form.contactName"
          :clearable="false"
          :autoHeight="true"
          :adjust-position="true"
          cursorSpacing="32"
        ></uni-easyinput>
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>

    <view class="block">
      <view style="">
        <text style="color: #f8285a; margin-right: 4px">*</text>
        负责人电话
      </view>
      <view class="value">
        <uni-easyinput
          type="text"
          placeholder="请输入负责人电话"
          :inputBorder="false"
          style="text-align: center"
          :value="form.environmentalContactPhone"
          @blur="proofphone"
          :clearable="false"
          :autoHeight="true"
          :adjust-position="true"
          cursorSpacing="32"
          ref="phoneRef"
        ></uni-easyinput>
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>

    <view class="upload-wrapper">
      <view
        class="wd-flex"
        style="
          justify-content: space-between;
          align-items: center;
          width: 100%;
        "
      >
        <view style="">
          <text style="color: #f8285a; margin-right: 4px">*</text>
          相关资质
        </view>
        <view
          class="wd-flex"
          style="color: #17c653; gap: 4px; align-items: center"
          @tap="addProve"
        >
          <u-icon name="plus-circle" color="#17C653" size="14"></u-icon>
          <text style="line-height: 1rem">新增资质</text>
        </view>
      </view>
      <view
        class="prove"
        v-for="(p, index) in prove"
        :key="index"
        v-if="prove.length > 0"
        @tap="editProve(p)"
      >
        <image
          :src="p.photo[0].url"
          style="
            width: 180rpx;
            height: 144rpx;
            flex-shrink: 0;
            border-radius: 8rpx;
          "
          mode="aspectFill"
        ></image>
        <view class="info">
          <view class="wd-flex" style="gap: 8px; align-items: center">
            <text class="label">资质名称</text>
            <view class="wd-font-800">
              {{
                $dict.echoDicValue(
                  dictMap.enterprise_qua,
                  p.qualificationName.toString()
                )
              }}
            </view>
          </view>
          <view class="wd-flex" style="gap: 8px; align-items: center">
            <text class="label">资质编号</text>
            <view
              class="wd-font-800"
              style="
                white-space: nowrap;
                text-overflow: ellipsis;
                max-width: 8rem;
                overflow: hidden;
              "
            >
              {{ p.enterpriseAuth }}
            </view>
          </view>
          <view class="wd-flex" style="gap: 8px; align-items: center">
            <text class="label">资质到期</text>
            <view class="wd-font-800">
              {{ $util.formatDate(p.expiryDate, 'YYYY/M/D') }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <cs-bottom-wrapper>
      <view class="operation">
        <button class="btn green" @tap="submit">提交审核</button>
      </view>
    </cs-bottom-wrapper>
  </view>
</template>

<script>
import { uploadFile } from '@/api/system/file.js'
import { getDictBatchByType } from '@/api/system/dict.js'
import {
  createEnterPrise,
  vertifyName,
  getEnterPrise,
  updateEnterprise
} from '@/api/enterprise/index.js'
import { getProveList } from '@/api/enterprise/prove.js'
export default {
  data() {
    return {
      form: {
        enterprisesName: '',
        address: '',
        gpsLocation: '',
        introduction: '',
        photo: [],
        tags: {},
        environmentalContactPhone: '',
        contactName: '',
        id: ''
      },
      dictMap: {},
      prove: [],
      inviteId: ''
    }
  },
  onLoad(res) {
    this.getDict()
    this.inviteId = res.inviteId
    if (res.id) {
      this.form.id = res.id
      this.init()
    }
    // 移除可能存在的旧监听器
    uni.$off('enterpriseIntroduce')
    uni.$off('enterpriseTag')
    uni.$off('prove')

    // 添加事件监听
    uni.$on('enterpriseIntroduce', data => {
      this.form.introduction = data.introduce
    })
    uni.$on('enterpriseTag', data => {
      this.form.tags = data
    })
    uni.$on('prove', data => {
      console.log('资质', this.prove)
      console.log('资质返回', data)
      if (this.form.id != '') {
        this.getProve()
      } else {
        this.prove.push(data)
      }
    })
  },
  onShow() {},
  methods: {
    proofName(v) {
      if (v.detail.value == '') return
      uni.showLoading({
        title: '加载中'
      })
      vertifyName({
        pageSize: -1,
        pageNo: 1,
        onlyEnterprisesName: v.detail.value,
        excludeEnterpriseId: this.form.id
      }).then(res => {
        if (res.data.total > 0) {
          uni.showToast({
            title: '企业名已存在',
            icon: 'none'
          })
          this.form.enterprisesName = ''
          this.$refs.nameRef.onClear()
        } else {
          this.form.enterprisesName = v.detail.value
        }
        uni.hideLoading()
      })
    },
    proofphone(v) {
      // 校验手机号
      const mobilePattern = /^1[3-9]\d{9}$/ // 中国手机号正则表达式
      if (!mobilePattern.test(v.detail.value)) {
        uni.showToast({
          title: '请输入有效的手机号',
          icon: 'none'
        })
        this.form.environmentalContactPhone = ''
        this.$refs.phoneRef.onClear()
      } else {
        this.form.environmentalContactPhone = v.detail.value
      }
    },
    async init() {
      const enterprise = await getEnterPrise(this.form.id)
      this.form = enterprise.data
      this.form.photo = enterprise.data.files
      const tag = {}
      enterprise.data.tagObjList.forEach(t => {
        tag[t.tagCode] = {
          name: t.tagName,
          value: t.id
        }
      })
      tag.qy = {
        name: this.$dict.echoDicValue(
          this.dictMap.enterprises_area,
          enterprise.data.region
        ),
        value: enterprise.data.region
      }
      this.form.tags = tag
      this.getProve()
    },
    async getProve() {
      console.log('getProve', this.prove)
      const load = this.$util.loading()
      const prove = await getProveList({ enterpriseId: this.form.id })
      load.close()
      this.prove = prove.data.list.map(p => {
        return {
          ...p,
          photo: p.files,
          expiryDate: this.$util.formatDate(p.expiryDate, 'YYYY-MM-DD')
        }
      })
    },
    /**
     * 获取字典
     */
    async getDict() {
      const dict = await getDictBatchByType({
        type: ['enterprise_qua', 'enterprises_area'].join(',')
      })
      this.dictMap = {
        ...dict.data
      }
    },
    chooseAddress() {
      uni.chooseLocation({
        success: res => {
          this.form.address = res.address
          this.form.gpsLocation = res.latitude + ',' + res.longitude
        }
      })
    },
    goIntruduce() {
      uni.navigateTo({
        url: `/sub/invite/enterpriseIntroduce?introduce=${this.form.introduction}`
      })
    },
    goTags() {
      uni.navigateTo({
        url: `/sub/invite/enterpriseTags?tags=${JSON.stringify(
          this.form.tags
        )}`
      })
    },
    /**
     * 选择图片并上传
     * @param {Object} e
     */
    async addEnterprisePhoto(e) {
      uni.showLoading({
        title: '上传中...'
      })
      e.file.forEach(p => {
        this.form.photo.push({
          ...p,
          status: 'uploading',
          message: '上传中'
        })
      })
      // 使用promise.all()方法上传到后端做统一接收
      await Promise.all(
        this.form.photo.map(async (p, i) => {
          if (p.status == 'uploading') {
            const res = await uploadFile({ name: `file`, filePath: p.url })
            return {
              ...res.data,
              status: 'success',
              message: ''
            }
          }
          return p
        })
      ).then(res => {
        this.form.photo = res
        uni.hideLoading()
      })
    },
    /**
     * 删除图片
     * @param {Object} e
     */
    delEnterprisePhoto(e) {
      this.form.photo.splice(e.index, 1)
    },
    addProve() {
      uni.navigateTo({
        url: `/sub/invite/prove?enterpriseId=${this.form.id}`
      })
    },
    editProve(prove) {
      uni.navigateTo({
        url: `/sub/invite/prove?prove=${JSON.stringify(prove)}`
      })
    },
    async submit() {
      const valide = await this.verifyForm()
      if (!valide) return
      const data = { ...this.form }
      data.region = data.tags.qy.id
      data.tagIds = [data.tags.hy.id, data.tags.st.id, data.tags.wr.id]
      data.fileIds = data.photo.map(i => i.id)
      data.userId = this.inviteId
      data.qualis = this.prove.map(i => {
        return {
          ...i,
          expiryDate: new Date(i.expiryDate).getTime(),
          files: i.photo.map(f => f.id)
        }
      })
      const load = this.$util.loading('上传中...')
      if (this.form.id) {
        updateEnterprise(data).then(res => {
          load.close()
          uni.showToast({
            icon: 'none',
            title: '操作成功'
          })
          uni.navigateBack()
        })
      } else {
        createEnterPrise(data).then(res => {
          load.close()
          uni.showToast({
            icon: 'none',
            title: '操作成功'
          })
          uni.navigateBack()
        })
      }
    },
    async verifyForm() {
      const msgMap = {
        enterprisesName: '请输入企业名',
        address: '请选择企业地址',
        gpsLocation: '请选择企业地址',
        introduction: '请填写企业介绍',
        photo: '最少上传一张企业照片',
        tags: '请选择企业标签',
        prove: '请填写企业资质',
        environmentalContactPhone: '请输入企业负责人',
        contactName: '请输入负责人电话'
      }
      const msg = []
      Object.keys(this.form).forEach(i => {
        if (!Object.hasOwn(msgMap, i)) {
          return false
        }
        if (!this.form[i]) {
          msg.push(msgMap[i])
        }
        if (typeof this.form[i] == 'Object' && this.form[i].length == 0) {
          msg.push(msgMap[i])
        }
      })
      if (this.prove.length == 0) {
        msg.push(msgMap.prove)
      }
      if (msg.length > 0) {
        uni.showToast({
          icon: 'none',
          title: msg.join('\n')
        })
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.view {
  padding: 12px;
  display: flex;
  flex-flow: column nowrap;
  gap: 12px;
  overflow: hidden;
  overflow-y: scroll;
  max-height: 100vh;
  padding-bottom: 12vh;
}
.block {
  display: flex;
  flex-flow: row nowrap;
  background-color: #fff;
  padding: 12px;
  border-radius: 8px;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  .label {
    font-family: UICTFontTextStyleBody;
    height: 1.4rem;
    min-height: 1.4rem;
  }
  .value {
    flex: 1;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    gap: 4px;
    .input-value {
      flex: 1;
      text-align: right;
      white-space: nowrap;
      text-overflow: ellipsis;
      cursor: auto;
      display: block;
      font-family: UICTFontTextStyleBody;
      height: 1.4rem;
      min-height: 1.4rem;
      overflow: hidden;
    }
    .input-textarea {
      flex: 1;
      display: -webkit-box;
      overflow: hidden;
      text-align: right;
      max-height: 3rem;
      text-overflow: ellipsis;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
      word-break: break-all;
      cursor: auto;
      display: block;
      font-family: UICTFontTextStyleBody;
      height: 1.4rem;
      min-height: 1.4rem;
      overflow: hidden;
    }
  }
}

.prove {
  border-radius: var(--Number-12px, 12px);
  border: 1px solid var(--LightMode-Grey-Grey-100, #f9f9f9);
  background: var(--LightMode-Light-Light, #fff);
  display: flex;
  padding: var(--Number-12px, 12px);
  align-items: center;
  gap: var(--Number-12px, 12px);
  font-size: 28rpx;
  flex-flow: row nowrap;
  .info {
    height: 72px;
    display: flex;
    flex-flow: column nowrap;
    justify-content: space-between;
  }
}

.upload-wrapper {
  display: flex;
  flex-flow: column nowrap;
  background-color: #fff;
  padding: 12px;
  border-radius: 8px;
  gap: 12px;
}

::v-deep .uni-easyinput__content-input {
  flex: 1;
  text-align: right;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: auto;
  display: block;
  font-family: UICTFontTextStyleBody;
  height: 1.4rem;
  min-height: 1.4rem;
  overflow: hidden;
  padding-right: 0;
}
::v-deep .uni-easyinput__placeholder-class {
  flex: 1;
  text-align: right;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: auto;
  display: block;
  font-family: UICTFontTextStyleBody;
  height: 1.4rem;
  min-height: 1.4rem;
  font-size: 14px;
  overflow: hidden;
}
.operation {
  padding: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  .btn {
    flex: 1;
    border-radius: 8px;
    display: flex;
    padding: 12px 0;
    align-items: center;
    justify-content: center;
  }
  .green {
    background-color: $cs-color-main;
    color: #fff;
  }
}
</style>