<template>
  <view class="view-container">
    <view class="container">
      <uni-steps :options="step.options" :active="step.active"></uni-steps>
      <scroll-view
        scroll-y="true"
        class="info-container"
        v-if="step.active == 0"
      >
        <u--form :model="info.form" ref="infoFormRef">
          <!-- 企业名称 -->
          <u-form-item label="名称" prop="enterprisesName" borderBottom>
            <u-input
              v-model="info.form.enterprisesName"
              border="none"
              placeholder="请输入名称"
            />
          </u-form-item>
          <!-- 企业类型 -->
          <u-form-item
            label="类型"
            prop="type"
            borderBottom
            @tap="showPicker('enterprises_type', 'type')"
          >
            <text v-if="info.form.type">
              {{
                $dict.echoDicValue(
                  dictMap.enterprises_type,
                  info.form.type.toString()
                )
              }}
            </text>
            <text class="placeholder" v-else>请选择类型</text>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <!-- 企业地址 -->
          <u-form-item
            label="地址"
            prop="address"
            borderBottom
            @click="chooseView(detail)"
          >
            <u-icon name="map" size="14" color="#17C653"></u-icon>
            <u-input
              v-model="info.form.address"
              border="none"
              placeholder="请输入地址"
            />
          </u-form-item>

          <!-- 环保负责人 -->
          <u-form-item
            label="环保负责人"
            prop="contactName"
            borderBottom
            labelWidth="80"
          >
            <u-input
              v-model="info.form.contactName"
              border="none"
              placeholder="请输入环保负责人姓名"
            />
          </u-form-item>
          <!-- 联系方式 -->
          <u-form-item
            label="联系方式"
            prop="environmentalContactPhone"
            borderBottom
            labelWidth="80"
          >
            <u-input
              v-model="info.form.environmentalContactPhone"
              border="none"
              placeholder="请输入联系方式"
            />
          </u-form-item>
          <!-- 成立时间 -->
          <u-form-item
            label="成立时间"
            prop="establishmentDate"
            borderBottom
            labelWidth="80"
            @tap="showCalendar('establishmentDate')"
          >
            <text v-if="info.form.establishmentDate">
              {{ info.form.establishmentDate }}
            </text>
            <text class="placeholder" v-else>请选择时间</text>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <!-- 企业照片 -->
          <u-form-item
            label="企业照片"
            prop="photo"
            borderBottom
            labelPosition="top"
            labelWidth="80"
          >
            <u-upload
              :fileList="info.form.photo"
              @afterRead="addEnterprisePhoto"
              @delete="delEnterprisePhoto"
              multiple
              :maxCount="3"
            ></u-upload>
          </u-form-item>
          <!-- 企业简介 -->
          <u-form-item
            label="简介"
            prop="introduction"
            borderBottom
            labelPosition="top"
          >
            <u--textarea
              v-model="info.form.introduction"
              placeholder="请输入简介"
              border="none"
              count="true"
            ></u--textarea>
          </u-form-item>
          <u-form-item>
            <u-button shape="circle" type="primary" @click="submitInfo">
              提交
            </u-button>
          </u-form-item>
        </u--form>
      </scroll-view>
      <view class="prove-container" v-else>
        <u--form
          :model="prove.form"
          ref="proveFormRef"
          v-if="prove.isEdit"
        >
          <u-form-item
            label="资质名称"
            prop="qualificationName"
            borderBottom
            labelWidth="80"
            @tap="showPicker('enterprise_qua', 'qualificationName')"
          >
            <text v-if="prove.form.qualificationName">
              {{
                $dict.echoDicValue(
                  dictMap.enterprise_qua,
                  prove.form.qualificationName.toString()
                )
              }}
            </text>
            <text class="placeholder" v-else>请选择资质名称</text>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item
            label="资质编号"
            prop="enterpriseAuth"
            borderBottom
            labelWidth="80"
          >
            <u-input
              v-model="prove.form.enterpriseAuth"
              border="none"
              placeholder="请输入编号"
            />
          </u-form-item>
          <u-form-item
            label="办理日期"
            prop="handleDate"
            borderBottom
            labelWidth="80"
            @tap="showCalendar('handleDate')"
          >
            <text v-if="prove.form.handleDate">
              {{ prove.form.handleDate }}
            </text>
            <text class="placeholder" v-else>请选择办理日期</text>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item
            label="到期日期"
            prop="expiryDate"
            borderBottom
            labelWidth="80"
            @tap="showCalendar('expiryDate')"
          >
            <text v-if="prove.form.expiryDate">
              {{ prove.form.expiryDate }}
            </text>
            <text class="placeholder" v-else>请选择到期日期</text>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <!-- 企业照片 -->
          <u-form-item
            label="资质照片"
            prop="photo"
            borderBottom
            labelPosition="top"
            labelWidth="80"
          >
            <u-upload
              :fileList="prove.form.photo"
              @afterRead="addEnterpriseProvePhoto"
              @delete="delEnterpriseProvePhoto"
              multiple
              :maxCount="3"
            ></u-upload>
          </u-form-item>
          <u-form-item
            label="描述"
            prop="qualificationDescription"
            borderBottom
            labelPosition="top"
          >
            <u--textarea
              v-model="prove.form.qualificationDescription"
              placeholder="请输入描述"
              border="none"
              count="true"
            ></u--textarea>
          </u-form-item>
        </u--form>
        <view class="prove-list" v-else>
          <view
            class="prove"
            v-for="prove in prove.list"
            :key="prove.id"
            @click="editProve(prove)"
          >
            <view class="wd-font-800" style="margin-bottom: 5px">
              {{
                $dict.echoDicValue(
                  dictMap.enterprise_qua,
                  prove.qualificationName.toString()
                )
              }}
            </view>
            <view class="">
              {{ $util.formatDate(prove.handleDate, 'YYYY年M月D日') }}
              {{ $util.formatDate(prove.expiryDate, 'YYYY年M月D日') }}
            </view>
          </view>
        </view>
        <view class="operation" v-if="prove.isEdit">
          <u-button shape="circle" type="primary" @click="submitProve">
            提交
          </u-button>
        </view>
        <view class="operation" v-else>
          <u-button shape="circle" type="info" @click="addProve">
            添加资质
          </u-button>
          <u-button
            shape="circle"
            type="success"
            v-if="invateId"
            @click="handlerDone"
          >
            完成
          </u-button>
        </view>
      </view>
    </view>
    <u-picker
      :show="picker.show"
      :columns="picker.data"
      @cancel="closePicker"
      closeOnClickOverlay
      keyName="label"
      ref="uPicker"
      @close="closePicker"
      @confirm="confirmPicker"
    ></u-picker>
    <uni-calendar
      ref="calendarRef"
      :insert="false"
      @confirm="confirmCalendar"
    />
  </view>
</template>

<script>
import { uploadFile } from '@/api/system/file.js'
import { getDictBatchByType } from '@/api/system/dict.js'
import { showConfirm } from '@/utils/common'
import { createEnterPrise } from '@/api/enterprise/index.js'
import {
  createProve,
  getProveList,
  updateProve
} from '@/api/enterprise/prove.js'
export default {
  data() {
    return {
      // 邀请人id
      invateId: undefined,
      // 企业基本信息
      info: {
        form: {
          id: '',
          enterprisesName: '',
          type: '', // 企业类型
          introduction: '', // 企业地址
          address: '', // 企业简介
          photo: [], // 企业照片
          contactName: '', // 环保负责人
          environmentalContactPhone: '', // 联系方式
          establishmentDate: '', // 成立时间
          gpsLocation: ''
        },
        rules: {
          enterprisesName: {
            required: true,
            message: '请输入企业名称',
            trigger: ['blur']
          },
          type: {
            type: 'string',
            required: true,
            message: '请选择企业类型',
            trigger: ['blur', 'change']
          },
          address: {
            required: true,
            message: '请输入企业地址',
            trigger: ['blur']
          },
          contactName: {
            required: true,
            message: '请输入环保负责人',
            trigger: ['blur']
          },
          environmentalContactPhone: {
            required: true,
            message: '请输入联系方式',
            trigger: ['blur']
          },
          photo: [
            {
              validator: value => {
                return (
                  Array.isArray(this.info.form.photo) &&
                  this.info.form.photo.length > 0
                )
              },
              message: '照片数组至少需要有一个元素'
            }
          ]
        }
      },
      // 字典
      dictMap: {},
      // 选择器
      picker: {
        show: false,
        // 做表单中键的缓存用
        key: null,
        data: []
      },
      // 日历控件
      calendar: {
        // 做表单中键的缓存用
        key: null
      },
      // 进度条
      step: {
        options: [
          {
            title: '基本信息'
          },
          {
            title: '资质信息'
          }
        ],
        active: 0
      },
      // 资质相关
      prove: {
        list: [],
        // 切换资质表单与列表的开关
        isEdit: true,
        loading: false,
        form: {
          enterpriseId: '',
          id: '',
          qualificationName: '',
          expiryDate: '',
          qualificationDescription: '',
          handleDate: '',
          enterpriseAuth: '',
          photo: []
        }
      }
    }
  },
  onLoad(res) {
    if (res.invateId) {
      console.log(res)
      this.invateId = res.invateId
    }
    this.getDict()
  },
  onReady() {
    this.step.active == 0 &&
      this.$refs.infoFormRef.setRules(this.info.rules)
    this.initProveList()
  },
  methods: {
    async chooseView() {
      uni.chooseLocation({
        success: res => {
          console.log(res)
          console.log(this.info)
          this.info.form.address = res.address
          this.info.form.gpsLocation = res.latitude + ',' + res.longitude
        }
      })
    },

    /**
     * 选择图片并上传
     * @param {Object} e
     */
    async addEnterpriseProvePhoto(e) {
      this.prove.form.photo = e.file.map(p => {
        console.log(p.url)
        return {
          ...p,
          status: 'uploading',
          message: '上传中'
        }
      })
      // 使用promise.all()方法上传到后端做统一接收
      await Promise.all(
        this.prove.form.photo.map(async (p, i) => {
          const res = await uploadFile({ name: `file`, filePath: p.url })
          return {
            ...res.data,
            status: 'success',
            message: ''
          }
        })
      ).then(res => {
        this.prove.form.photo = res
        console.log('pthoto3', this.info.form.photo)
      })
    },
    /**
     * 删除图片
     * @param {Object} e
     */
    delEnterpriseProvePhoto(e) {
      this.prove.form.photo.splice(e.index, 1)
    },

    /**
     * 选择图片并上传
     * @param {Object} e
     */
    async addEnterprisePhoto(e) {
      this.info.form.photo = e.file.map(p => {
        console.log(p.url)
        return {
          ...p,
          status: 'uploading',
          message: '上传中'
        }
      })
      // 使用promise.all()方法上传到后端做统一接收
      await Promise.all(
        this.info.form.photo.map(async (p, i) => {
          const res = await uploadFile({ name: `file`, filePath: p.url })
          return {
            ...res.data,
            status: 'success',
            message: ''
          }
        })
      ).then(res => {
        this.info.form.photo = res
        console.log('pthoto3', this.info.form.photo)
      })
    },
    /**
     * 删除图片
     * @param {Object} e
     */
    delEnterprisePhoto(e) {
      this.info.form.photo.splice(e.index, 1)
    },

    /**
     * 弹出选择器
     * @param {String} type 字典类型
     * @param {String} key 表单中需要赋值的健
     */
    showPicker(type, key) {
      // 取出字典中type对应的列表并赋值给选择器的列表
      this.picker.data.push(this.dictMap[type])
      this.picker.key = key
      this.picker.show = true
    },
    /**
     * 获取字典
     */
    async getDict() {
      const dict = await getDictBatchByType({
        type: ['enterprises_type', 'enterprise_qua'].join(',')
      })
      this.dictMap = {
        ...dict.data
      }
    },
    /**
     * 选择器确认回调
     * @param {Object} e
     */
    confirmPicker(e) {
      const { value } = e
      if (this.step.active == 1) {
        // 若是步骤索引为1 则向资质表单赋值
        this.prove.form[this.picker.key] = value[0].value
      } else {
        // 若是步骤索引为0 则向企业基本信息表单赋值
        this.info.form[this.picker.key] = value[0].value
      }
      this.closePicker()
    },
    /**
     * 关闭选择器
     */
    closePicker() {
      this.picker = {
        show: false,
        key: '',
        data: []
      }
    },
    /**
     * 显示日历
     * @param {Object} key 表单中需要赋值的键
     */
    showCalendar(key) {
      this.$refs.calendarRef.open()
      this.calendar = {
        key
      }
    },
    /**
     * 日历选中之后的回调
     * @param {Object} e
     */
    confirmCalendar(e) {
      if (this.step.active == 1) {
        // 若是步骤索引为1 则向资质表单赋值
        this.prove.form[this.calendar.key] = e.fulldate
      } else {
        // 若是步骤索引为0 则向企业基本信息表单赋值
        this.info.form[this.calendar.key] = e.fulldate
      }
      this.closeCalendar()
    },
    /**
     * 关闭日历
     */
    closeCalendar() {
      this.calendar = {
        key: null
      }
    },
    /**
     * 企业基本信息表单提交事件
     */
    submitInfo() {
      this.$refs.infoFormRef.validate().then(async res => {
        this.handlerInfoApi()
      })
    },
    /**
     * 触发创建企业接口
     */
    async handlerInfoApi() {
      const data = this.info.form
      data.fileIds = this.info.form.photo.map(p => p.id)
      data.userId = this.invateId
      let enterprise
      if (this.info.form.id) {
        // 修改企业
      } else {
        enterprise = await createEnterPrise(data)
        //新增企业时需要将返回的id存到表单中,作为资质上传、修改的关联id
        this.info.form.id = enterprise.data
        uni.showToast({
          icon: 'success',
          title: '操作成功'
        })
        // 将步骤显示到下一个
        this.step.active = 1
      }
      this.initProveList()
    },
    /**
     * 添加资质
     */
    addProve() {
      this.prove.isEdit = true
    },
    /**
     * 提交资质
     */
    submitProve() {
      this.handlerProveApi()
    },
    /**
     * 初始化资质列表
     */
    async initProveList() {
      this.prove.loading = true
      const res = await getProveList({
        pageSize: -1,
        enterpriseId: this.info.form.id
      })
      this.prove.list = res.data.list
      this.prove.loading = false
    },
    /**
     * 触发资质新增、修改的接口
     */
    async handlerProveApi() {
      let prove
      let data = this.prove.form
      data.enterpriseId = this.info.form.id
      data.files = this.prove.form.photo.map(p => p.id)
      if (data.id) {
        prove = await updateProve(data)
      } else {
        prove = await createProve(data)
      }
      this.prove.isEdit = false
      uni.showToast({
        icon: 'success',
        title: '操作成功'
      })
      this.prove.form = {
        enterpriseId: '',
        id: '',
        qualificationName: '',
        expiryDate: '',
        qualificationDescription: '',
        handleDate: '',
        enterpriseAuth: ''
      }
      this.initProveList()
    },
    /**
     * 编辑资质
     * @param {Object} prove 列表中的资质实例对象
     */
    editProve(prove) {
      this.prove.form = prove
      this.prove.form.handleDate = this.$util.formatDate(
        prove.handleDate,
        'YYYY-MM-DD'
      )
      this.prove.form.expiryDate = this.$util.formatDate(
        prove.expiryDate,
        'YYYY-MM-DD'
      )
      this.prove.isEdit = true
    },
    /**
     * 完成事件
     */
    handlerDone() {
      uni.navigateTo({
        url: '/sub/common/waiting'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.view-container {
  height: 100vh;
}
.container {
  height: 100%;
  background-color: #fff;
  padding: 10px;
  overflow: hidden;
  display: flex;
  flex-flow: column nowrap;
  height: 100%;
  .info-container {
    padding: 0 10px;
    margin-top: 10px;
  }
  .prove-container {
    flex: 1;
    position: relative;
    padding: 0 10px;
    margin-top: 10px;
    .prove-list {
      .prove {
        margin-bottom: 10px;
        padding: 10px 0;
        border-bottom: 1px dashed #c0c4cc;
      }
    }
    .operation {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      padding: 10px;
      display: flex;
      flex-flow: row nowrap;
      gap: 10px;
    }
  }
}
.placeholder {
  color: #c0c4cc;
}
::v-deep .u-form-item__body {
  gap: 5px;
}
.address {
}
</style>