<template>
  <el-drawer
    title="医生详情"
    :visible.sync="drawer"
    size="80%"
    @close="$emit('cancel')"
  >
    <divider-container title="基本信息" />

    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="140px">
      <el-form-item label="医生名称" prop="name">
        <el-input v-model="form.name" style="max-width: 300px;" autocomplete="off" :maxlength="50" placeholder="不超过50个字符" />
      </el-form-item>
      <el-form-item label="所属医院" prop="hospital">
        <el-input v-model="form.hospital" style="max-width: 300px;" autocomplete="off" :maxlength="50" placeholder="不超过50个字符" />
      </el-form-item>
      <el-form-item label="所属科室" prop="dept">
        <el-input v-model="form.dept" style="max-width: 300px;" autocomplete="off" :maxlength="200" placeholder="不超过200个字符" />
      </el-form-item>
      <el-form-item label="上传照片" prop="headUrl">
        <upload v-model="form.headUrl" params="prefix=/doctor" />
      </el-form-item>
      <el-form-item label="医生职称/职务">
        <el-tag
          v-for="tag in form.tagOptions"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新职务</el-button>
      </el-form-item>
      <el-form-item label="医生资质" prop="desc">
        <el-input v-model="form.desc" style="max-width: 500px;" type="textarea" :rows="5" autocomplete="off" />
      </el-form-item>
      <el-form-item label="是否置顶" prop="isTop">
        <el-checkbox v-model="form.isTop">置顶</el-checkbox>
      </el-form-item>
    </el-form>

    <el-row v-if="modalType !== 'add'">
      <divider-container title="关联内容" />

      <el-row>
        <el-col :span="22" :offset="1">
          <div class="search-box">
            <el-input v-model="search.input" class="search-input" placeholder="请输入内容名称搜索">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
            </el-input>
            <table-with-page :columns="columns" :items="items" :pagination="pagination" :page-change="pageChange" min-height="300px">
              <template #btn-box="scope">
                <el-popconfirm title="确定删除吗？" @onConfirm="handleDeleteSelected(scope.selected)">
                  <el-button slot="reference" type="danger">删除</el-button>
                </el-popconfirm>
              </template>
            </table-with-page>
          </div>
        </el-col>
      </el-row>
    </el-row>

    <!-- <divider-container title="发布渠道" class="mt-60">
      <el-row :gutter="10">
        <el-col class="txt-right" :span="4">勾选发布渠道：</el-col>
        <el-col :span="20">
          <SetCheckBoxWithTop
            v-model="form.channels"
            :options="options"
          />
        </el-col>
      </el-row>
    </divider-container> -->

    <div class="flex-end mcol-10 btn-footer">
      <el-button type="primary" @click="handleSubmit('ruleForm')">保存</el-button>
      <el-button v-if="modalType === 'edit'" type="danger" @click="handleDelete">删除</el-button>
      <el-button @click="drawer = false">取消</el-button>
    </div>
  </el-drawer>
</template>

<script>
import { format, cutUrl } from '@/utils'
import MODULETYPE from '@/const/moduleType'
import { UPLOAD_URL_DEMO } from '@/const/urlKey'

import { getItem, saveItem, getArticleList, deleteDoctorInArticle, deleteDoctorsInArticle, deleteDoctor } from '@/model/doctor'
import EMITKEY from '@/const/emitNameKey'

export default {
  name: 'DoctorItem',

  props: {
    id: {
      type: String,
      default: ''
    },
    modalType: {
      type: String,
      default: 'add'
    }
  },

  data() {
    const validateImg = (rule, value, callback) => {
      if (!Array.isArray(value)) return callback(new Error('数据出错，请重新上传'))
      if (value.length < 1) return callback(new Error('请先上传图片'))
      return callback()
    }

    return {
      drawer: true,
      info: {},

      form: {
        name: '',
        hospital: '',
        dept: '',
        headUrl: [{ url: UPLOAD_URL_DEMO }],
        desc: '',
        channels: [],
        isTop: false,
        tagOptions: []
      },
      rules: {
        name: [{ required: true, message: '请输入医生名称', trigger: 'blur' }],
        headUrl: [{ required: true, validator: validateImg, trigger: 'change' }]
      },

      columns: [
        {
          key: 'selection'
        }, {
          key: 'contentType',
          name: '内容载体',
          minWidth: '80'
        }, {
          key: 'id',
          name: '内容ID',
          minWidth: '250'
        }, {
          key: 'title',
          name: '内容名称',
          minWidth: '200'
        }, {
          key: 'isReleaseF',
          name: '发布状态',
          minWidth: '100'
        }, {
          key: 'isFeatureF',
          name: '是否精选',
          minWidth: '80'
        }, {
          key: 'action',
          name: '操作',
          minWidth: '80',
          render: (h, { row }) => {
            const action = []
            action.push(h('el-popconfirm', {
              props: {
                title: '确定删除这项吗？'
              },
              on: {
                onConfirm: () => this.handleDeleteSelectItem(row)
              }
            }, [
              h('el-button', {
                slot: 'reference',
                props: {
                  type: 'danger'
                }
              }, '删除')
            ]))
            return h('div', action)
          }
        }
      ],
      pagination: {
        page: 1,
        total: 0,
        pageSize: 10
      },
      search: {
        input: ''
      },
      filter: {
        'input': ''
      },
      options: MODULETYPE.DOCTOR_ADD_TYPE,
      val: [],
      items: [],

      inputVisible: false,
      inputValue: ''
    }
  },

  watch: {
  },

  mounted() {
    this.id && this.loadData()
  },

  methods: {
    async loadData() {
      const { success, data, msg } = await getItem({
        id: this.id
      })
      if (success) {
        Object.assign(this.form, data)
        this.reload()
      } else {
        this.$message.error(msg)
      }
    },

    reload() {
      this.pageChange(this.pagination.page)
    },

    handleSearch() {
      this.filter['searchText'] = this.search.input
      this.pageChange(1)
    },

    async pageChange(page) {
      this.pagination.page = page

      const options = format({
        doctorId: this.id,
        data: {
          ...this.filter
        },
        'pageNum': this.pagination.page,
        'pageSize': this.pagination.pageSize
      })
      const { success, data, msg } = await getArticleList(options)
      if (success) {
        const { items, total } = data
        if (items.length === 0 && this.page > 1) {
          this.pageChange(1)
        } else {
          this.items.splice(0, this.items.length)
          this.items.push(...Object.freeze(items))
          this.pagination.total = total
        }
      } else {
        this.$message.error(msg || '系统报错~')
      }
    },

    async handleDeleteSelectItem(row) {
      const { success, msg } = await deleteDoctorInArticle({
        articleId: row.id
      })
      if (success) {
        this.$message.success('删除成功~')
        this.reload()
      } else {
        this.$message.error(msg)
      }
    },

    async handleDeleteSelected(selected) {
      const { success, msg } = await deleteDoctorsInArticle({
        data: {
          ids: selected.map(x => x.id)
        }
      })
      if (success) {
        this.$message.success('删除成功~')
        this.reload()
      } else {
        this.$message.error(msg)
      }
    },

    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveData()
        }
      })
    },

    async saveData() {
      const tmp = this.form
      const options = {
        id: this.id,
        data: {
          ...tmp,
          description: tmp.desc,
          headUrl: cutUrl(tmp.headUrl[0].url), // tmp.headUrl[0]
          isShow: true,
          title: tmp.tagOptions.join(',')
          // ...this.solveChannels(tmp.channels)
        }
      }
      const { success, msg } = await saveItem(options)
      if (success) {
        this.$message.success('操作成功~')
        this.drawer = false
        this.bus.$emit(EMITKEY.DOCTORRELOAD)
      } else {
        this.$message.error(msg)
      }
    },

    solveChannels(arr) {
      const result = {
        channels: [],
        channelsIsTop: []
      }
      // 找出选中的值，排除置顶字段
      const list = arr.filter(x => {
        if (x.indexOf('_top') === -1) {
          return x
        }
      })
      // 分别匹配是否置顶
      list.forEach(x => {
        result.channels.push(x)
        if (arr.findIndex(y => y === `${x}_top`) !== -1) {
          result.channelsIsTop.push(true)
        } else {
          result.channelsIsTop.push(false)
        }
      })
      return result
    },

    async handleDelete() {
      const { success, msg } = await deleteDoctor({
        id: this.id
      })
      if (success) {
        this.$message.success('删除成功~')
        this.drawer = false
        this.bus.$emit(EMITKEY.DOCTORRELOAD)
      } else {
        this.$message.error(msg)
      }
    },

    handleClose(tag) {
      this.form.tagOptions.splice(this.form.tagOptions.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.form.tagOptions.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 180px;
  margin-left: 10px;
  vertical-align: bottom;
}

.flex-end {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.mt-60 {
  margin-top: 60px;
}
.mcol-10 {
  margin-top: 10px;
  margin-bottom: 10px;
}
.btn-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.mcol-20 .el-row {
  font-size: 14px;
  line-height: 1.7;
  padding-top: 14px;
}
.search-box {
  border: 1px #DCDEE2 solid;
  padding: 5px;
}
.search-box .search-input {
  margin: 0 5px;
  max-width: 200px;
}
.btn-footer {
  margin-right: 15px;
}
</style>
