<template>
  <div class="doctor-edit">
    <el-form ref="submitForm" class="doctor-edit-form" label-width="140px" :model="formData" :rules="rules">
      <el-form-item label="操作师姓名:" prop="doctorName">
        <el-input v-model="formData.doctorName" type="text" placeholder="请输入操作师姓名" :maxlength="30" />
      </el-form-item>
      <el-form-item label="从业资格证编号:" prop="certificateNo">
        <el-input v-model="formData.certificateNo" placeholder="请输入从业资格证编号" />
      </el-form-item>
      <!-- <el-form-item label="所在机构:" prop="clubName">
        <el-input v-model="formData.clubName" placeholder="请输入机构名称" />
      </el-form-item> -->
      <el-form-item label="所在机构:" :prop="formData.authId ? 'authId' : 'clubName'">
        <el-select
          v-model="selectClub"
          style="width: 100%"
          filterable
          allow-create
          default-first-option
          placeholder="所在机构"
          @change="onDoctorClubChange"
        >
          <el-option v-for="item in clubList" :key="item.authId" :label="item.authParty" :value="item.authId" />
        </el-select>
        <el-input v-show="false" v-model="formData.clubName" />
      </el-form-item>
      <el-form-item label="形象照:" prop="doctorImage">
        <div class="form-label-tip">（提示：医师形象照片）</div>
        <el-input v-show="false" v-model="formData.doctorImage" />
        <upload-image
          tip="提示：上传操作师个人照片，建议尺寸：200px * 200px"
          :image-list="doctorImageList"
          :before-upload="beforeDoctorImageUpload"
          @success="uploadDoctorImageSuccess"
          @remove="handleDoctorImageRemove"
        />
      </el-form-item>
      <el-form-item label="简介图:" prop="banner">
        <div class="form-label-tip">（提示：工作或其他个人介绍图，至少上传一张，限6张）</div>
        <el-input v-show="false" v-model="formData.banner" />
        <upload-image
          tip="至少上传一张机构门店图，最多上传6张；建议尺寸：542px * 542px"
          :image-list="bannerList"
          :limit="6"
          :before-upload="beforeBannerUpload"
          @success="uploadBannerSuccess"
          @remove="handleBannerRemove"
        />
      </el-form-item>

      <el-form-item label="操作师标签:" prop="tagList">
        <el-input v-show="false" v-model="formData.tagList" />
        <div class="tag-control">
          <input
            v-model="tagName"
            class="el-input el-input__inner"
            placeholder="输入标签名后点击添加按钮(15个字符内)"
            maxlength="15"
          >
          <el-button type="primary" @click="addTag">添加</el-button>
        </div>
        <div class="tag-list">
          <el-tag v-for="(item, index) in addTagList" :key="index" closable @close="onTagClose(index)">{{
            item
          }}</el-tag>
        </div>
      </el-form-item>

      <el-form-item label="自定义属性:">
        <doctor-custom-items v-if="!isRequest" ref="customItems" @change="customItemsChange" />
      </el-form-item>

      <el-form-item label="具备操作资格设备:" prop="equipment">
        <el-input v-show="false" v-model="formData.equipment" />
        <device-section v-if="!isRequest" ref="subForm" :list="deviceList" @change="deviceListDataChange" />
      </el-form-item>
    </el-form>
    <div class="submit-btn">
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button type="warning" @click="navigateBack()">返回</el-button>
    </div>
  </div>
</template>

<script>
import { Promise } from 'jszip/lib/external'
import { mapGetters } from 'vuex'
import { DeviceSection, DoctorCustomItems } from '@/views/components'
import UploadImage from '@/components/UploadImage'
import { doctorSave, doctorFormData, fetchDoctorClubList } from '@/api/doctor'

export default {
  components: { DeviceSection, UploadImage, DoctorCustomItems },
  data() {
    var validateCertificateNo = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('从业资格证编号不能为空'))
      } else {
        if (/^[a-z|A-Z|0-9]{1,}$/.test(value)) {
          callback()
        } else {
          callback(new Error('从业资格证编号格式不正确'))
        }
      }
    }

    return {
      isRequest: true,
      editType: 'add',
      doctorId: '',
      point: {},
      disabled: false,
      formData: {
        authId: -1,
        doctorType: 1,
        doctorName: '',
        certificateNo: '',
        clubName: '',
        banner: '',
        doctorImage: '',
        equipment: '',
        tagList: ''
      },
      rules: {
        doctorName: [
          { required: true, message: '医师姓名不能为空', trigger: ['blur', 'change'] },
          { maxlength: 30, message: '最大长度为30个字符', trigger: ['blur', 'change'] }
        ],
        certificateNo: [{ required: true, validator: validateCertificateNo, trigger: ['blur', 'change'] }],
        clubName: [{ required: true, message: '所在机构不能为空', trigger: ['blur', 'change'] }],
        authId: [{ required: true, message: '所在机构不能为空', trigger: ['change'] }],
        doctorImage: [{ required: true, message: '请上传医师照片', trigger: 'change' }],
        banner: [{ required: true, message: '请上传至少一张轮播图', trigger: 'change' }],
        equipment: [{ required: true, message: '具备操作资格设备不能为空', trigger: 'change' }],
        tagList: [{ required: true, message: '医师标签不能为空', trigger: 'change' }]
      },
      // logo图片列表
      doctorImageList: [],
      // banner图片列表
      bannerList: [],
      // 资格仪器列表
      deviceList: [],
      // 机构列表
      clubList: [],
      selectClub: '',
      // 添加标签名
      tagName: '',
      // 医师标签列表
      addTagList: [],
      // 自定义参数列表
      paramList: []
    }
  },
  computed: {
    ...mapGetters(['token', 'authUserId']),
    // 图片上传
    action() {
      return process.env.VUE_APP_UPLOAD_API + '/upload/image'
    },
    headers() {
      return {
        'X-Token': this.token
      }
    }
  },
  watch: {
    addTagList: {
      handler: function(nVal) {
        this.formData.tagList = this.addTagList.join(',')
      },
      deep: true
    }
  },
  created() {
    this.doctorId = parseInt(this.$route.query.id)
    this.editType = this.$route.query.type || 'edit'
    this.fetchDoctorClubList()
    this.initFormData()
  },
  methods: {
    // 添加标签
    addTag() {
      this.addTagList.push(this.tagName.trim())
      this.tagName = ''
    },

    // 删除标签
    onTagClose(index) {
      this.addTagList.splice(index, 1)
    },

    // 选择医师机构
    onDoctorClubChange(value) {
      if (typeof value === 'number') {
        this.formData.authId = value
        this.formData.clubName = '非自定义'
      } else {
        this.formData.authId = -1
        this.formData.clubName = value
      }
    },

    // 自定义字段变化
    customItemsChange(list) {
      console.log(list)
      this.paramList = list
    },

    // 具备操作资格设备列表数据变化
    deviceListDataChange(list) {
      this.deviceList = list
      this.formData.equipment = list.length || ''
    },

    // 表单数据回显
    initFormData() {
      if (this.editType !== 'edit') {
        this.$nextTick(() => {
          this.$refs.customItems.setParamsItem([
            {
              name: '',
              content: ''
            }
          ])
        })
        this.isRequest = false
        return
      }
      doctorFormData({ doctorId: this.doctorId }).then((res) => {
        this.setFormData(res.data)
      })
    },

    // 设置表单数据
    setFormData(data) {
      this.formData.doctorName = data.doctorName
      this.formData.certificateNo = data.certificateNo
      this.formData.clubName = data.clubName
      this.formData.doctorImage = data.doctorImage
      this.formData.authId = data.authId || -1

      this.formData.banner = data.bannerList.length
      this.formData.equipmentList = data.equipmentList.length
      this.doctorImageList.push({ url: data.doctorImage, name: 'doctor' })
      this.bannerList = data.bannerList.map((item) => ({ url: item, name: '' }))
      this.deviceList = data.equipmentList
      this.paramList = data.paramList
      this.addTagList = data.tagList

      this.selectClub = !data.authId ? data.clubName : data.authId

      this.isRequest = false

      this.$nextTick(() => {
        this.$refs.customItems.setParamsItem(this.paramList)
      })
    },

    // 提交表单验证
    submit() {
      Promise.all([
        this.$refs.subForm.valideAllForm(),
        this.$refs.submitForm.validate(),
        this.$refs.customItems.valideAllForm()
      ]).then((res) => {
        this.save()
      })
    },

    // 保存
    save() {
      const authUserId = this.authUserId
      const data = {
        authUserId,
        createBy: authUserId,
        doctorId: this.doctorId,
        doctorName: this.formData.doctorName,
        certificateNo: this.formData.certificateNo,
        clubName: this.formData.clubName,
        doctorImage: this.formData.doctorImage,
        tagList: this.addTagList,
        authId: this.formData.authId,
        doctorType: this.formData.doctorType,
        paramList: this.paramList
      }

      console.log(this.formData)

      data.bannerList = this.bannerList.map((item) => (item.response ? item.response.data : item.url))
      data.equipmentList = this.deviceList.map((item) => ({
        equipmentName: item.equipmentName,
        brand: item.brand,
        image: item.image
      }))
      doctorSave(data).then((res) => {
        this.$message.success('保存成功')
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.push('/personnel/operate/list')
      })
    },

    // 获取医师机构列表
    async fetchDoctorClubList() {
      try {
        const res = await fetchDoctorClubList({ authUserId: this.authUserId })
        this.clubList = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 医师照片上传
    uploadDoctorImageSuccess({ response, file, fileList }) {
      this.doctorImageList = fileList
      this.formData.doctorImage = response.data
    },
    handleDoctorImageRemove({ file, fileList }) {
      this.doctorImageList = fileList
      this.formData.doctorImage = ''
    },
    beforeDoctorImageUpload(file) {
      const flag = file.size / 1024 / 1024 < 2
      if (!flag) {
        this.$message.error('上传医师照片大小不能超过 2MB!')
      }
      return flag
    },

    // banner上传
    uploadBannerSuccess({ response, file, fileList }) {
      this.bannerList = fileList
      this.formData.banner = fileList.length || ''
    },
    handleBannerRemove({ file, fileList }) {
      this.bannerList = fileList
      this.formData.banner = fileList.length || ''
    },
    beforeBannerUpload(file) {
      const flag = file.size / 1024 / 1024 < 2
      if (!flag) {
        this.$message.error('上传banner图片大小不能超过 2MB!')
      }
      return flag
    }
  }
}
</script>

<style lang="scss" scoped>
.doctor-edit {
  margin-bottom: 80px;
}

.doctor-edit-form {
  width: 650px;
  margin: 0 auto;
  margin-top: 80px;
}
.submit-btn {
  text-align: center;
  .el-button {
    width: 140px;
  }
}

.tag-control {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-input {
    flex: 1;
    margin-right: 16px;
  }
}

.tag-list {
  padding-top: 8px;

  .el-tag {
    margin-right: 6px;
  }
}
</style>
