<template>
  <el-dialog
    :title="refList.title"
    :visible.sync="dialogVisible"
    width="36%"
    :before-close="handleClose"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :append-to-body="true"
    v-loading.fullscreen.lock="fullscreenLoading"
  >
    <el-form :model="form" ref="form" :rules="rules" label-width="120px">
      <el-form-item label="分类名称：" prop="typeId">
        <el-select
          :disabled="!refList.show"
          filterable
          placeholder="请选择"
          v-model="form.typeId"
          @visible-change="visbleChange"
          @change="classifyChange"
        >
          <el-option
            v-for="(item, index) in classifyList"
            :key="index"
            :label="item.name"
            :value="item.typeId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上传文件：" prop="docUrl">
        <div>
          <el-upload
            class="upload-demo"
            :action="url"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :before-upload="beforeAvatarUpload"
            accept=".pdf, application/pdf"
          >
            <el-button
              size="small"
              style="background: #579ef8; border-color: #579ef8"
              type="primary"
              >点击上传</el-button
            >
            <div slot="tip" class="el-upload__tip">
              仅支持pdf文件,文件名称保存时生效
            </div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="文件名称：" prop="name">
        <el-input
          class="maxlength-input"
          placeholder="请输入"
          maxlength="64"
          show-word-limit
          v-model.trim="form.name"
        ></el-input>
      </el-form-item>
      <el-form-item prop="status">
        <template slot="label"
          ><span style="word-spacing: 22px">状&emsp;态</span>：</template
        >
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        style="margin-bottom: 20px"
        label
        v-for="(item, index) in form.role"
        :key="index"
      >
        <template v-if="index == 0" slot="label">
          <span>可访问手机号：</span>
        </template>
        <div class="form_item_content">
          <el-input
            clearable
            placeholder="请输入手机号"
            v-onlyInt
            maxlength="11"
            v-model="item.value"
          ></el-input>
          <i class="iconfont icon-a-zu903" @click="addjurisdiction"></i>
          <i
            class="iconfont icon-a-zu904"
            v-if="form.role.length != 1"
            @click="deletjurisdiction(index)"
          ></i>
        </div>
      </el-form-item>
      <el-form-item label="可访问群组：">
        <el-select
          v-model="form.conversationList"
          multiple
          collapse-tags
          placeholder="请选择"
        >
          <el-option
            v-for="item in conversationList"
            :key="item.openConversationId"
            :label="item.conversationName"
            :value="item.openConversationId"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button
        size="small"
        style="margin-left: 60px"
        type="primary"
        @click="addList('form')"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import * as api from '@/api/api'
export default {
  data() {
    return {
      fullscreenLoading: false,
      dialogVisible: false,
      form: {
        docUrl: '',
        id: '',
        linkUrl: '',
        name: '',
        status: 1,
        typeId: '',
        role: [{ value: '' }],
        conversationList: []
      },
      conversationList: [],
      refList: {},
      fileList: [],
      classifyList: [],
      rules: {
        typeId: [
          { required: true, trigger: 'change', message: '请选择分类名称' }
        ],
        name: [{ required: true, trigger: 'blur', message: '请输入文件名称' }],
        docUrl: [{ required: true, trigger: 'click', message: '请上传文件' }]
      },
      url: window.global_config.BASE_URL + '/api/file/local/upload'
    }
  },
  methods: {
    /**
     * @method 关闭弹框
     * **/
    handleClose() {
      this.dialogVisible = false
      this.$parent.search()
      this.form = {
        docUrl: '',
        id: '',
        linkUrl: '',
        name: '',
        status: 1,
        typeId: '',
        fileSize: '',
        role: [{ value: '' }],
        conversationList: []
      }
      this.fileList = []
      this.$refs['form'].resetFields()
    },
    /**
     * @method 打开文件弹框
     * **/
    openClose(val) {
      if (val) {
        this.refList = val
        if (val.id) {
          this.visbleChange(true)
          this.details()
        }
        this.conversationGetDropList()
      }
      this.dialogVisible = true
    },
    /**
     * @method 详情
     * **/
    details() {
      api.GET('/doc/getDetail', { id: this.refList.id }).then(data => {
        if (data.code == 0) {
          this.form = data.data
          let role = []
          if (this.form.role && this.form.role.length != 0) {
            this.form.role.forEach(item => {
              role.push({ value: item })
            })
            this.form.role = role
          } else {
            this.form.role = [{ value: '' }]
          }
          let conversationList = []
          if (this.form.conversationList) {
            this.form.conversationList.forEach(item => {
              conversationList.push(item.openConversationId)
            })
          }
          this.form.conversationList = conversationList
          this.fileList = [{ name: this.form.name, url: this.form.docUrl }]
        }
      })
    },
    /**
     * @method 分类下拉列表
     * **/
    visbleChange(val) {
      if (val) {
        api.GET('/doc/type/dropListAll').then(data => {
          if (data.code == 0) {
            this.classifyList = data.data
          }
        })
      }
    },
    /**
     * @method 分类选择
     * **/
    classifyChange(val) {
      this.form.conversationList = []
      this.classifyList.find(item => {
        if (item.typeId == val) {
          this.form.linkUrl = item.linkUrl
          if (item.list) {
            item.list.map(val => {
              this.form.conversationList.push(val.openConversationId)
            })
          }
        }
      })
      this.detailClassifica(val)
    },
    /**
     * @method 分类详情
     * **/
    detailClassifica(val) {
      let code = {
        typeId: val
      }
      api.POST('/doc/type/detail', code).then(data => {
        if (data.code == 0) {
          this.form.role = data.data.role
          let role = []
          if (this.form.role && this.form.role.length != 0) {
            this.form.role.forEach(item => {
              role.push({ value: item })
            })
            this.form.role = role
          } else {
            this.form.role = [{ value: '' }]
          }
        }
      })
    },
    /**
     * @method 上传
     * **/
    // api_import(file) {
    //   const files = {
    //     file: file.file
    //   }
    //   api
    //     .IMPORT('/api/file/local/upload', files)
    //     .then(data => {
    //       if (data.code == 0) {
    //         this.form.name == ''
    //           ? (this.form.name = file.file.name)
    //           : this.form.name

    //         // data.data.name = this.form.name
    //         // this.fileList = [data.data]
    //         this.form.docUrl = data.data.url
    //         this.form.fileSize = data.data.size
    //         this.$message.success('上传成功')
    //       }
    //     })
    //     .catch(() => {
    //       this.fileList = []
    //     })
    // },
    /**
     * @method 文件上传限制
     * **/
    handleExceed(files, fileList) {
      if (fileList.length == 1) {
        this.$message.warning('只能上传单个文件')
      }
    },
    /**
     * @method 上传成功
     * **/
    handleSuccess(file, fileList) {
      this.form.name == ''
        ? (this.form.name = fileList.name.split('.pdf')[0].substring(0, 64))
        : this.form.name
      file.data.name = this.form.name
      this.fileList = [file.data]
      this.form.docUrl = file.data.url
      this.form.fileSize = file.data.size
      this.$message.success('上传成功')
    },
    /**
     * @method 文件删除
     * **/
    handleRemove(files, fileList) {
      this.form.name = ''
      this.fileList = fileList
      this.form.docUrl = ''
      this.form.fileSize = ''
    },
    /**
     * @method 上传限制
     * **/
    beforeAvatarUpload(file) {
      const ispaf = file.type === 'application/pdf'

      if (!ispaf) {
        this.$message.error('上传文件只能是 PDF 格式!')
      }
      return ispaf
    },
    /**
     * @method 提交确定
     * **/
    addList(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.fullscreenLoading = true
          let role = []
          for (let item of this.form.role) {
            if (item.value && item.value.length != 11) {
              this.fullscreenLoading = false
              return this.$message.warning('请输入正确的手机号')
            }
            if (item.value) {
              role.push(item.value)
            }
          }
          let conversationList = []
          if (this.conversationList) {
            this.conversationList.forEach(item => {
              if (
                this.form.conversationList.find(
                  ltem => item.openConversationId == ltem
                )
              ) {
                conversationList.push({
                  chatId: item.chatId,
                  openConversationId: item.openConversationId
                })
              }
            })
          }
          let code = {
            docUrl: this.form.docUrl,
            linkUrl: this.form.linkUrl,
            name: this.form.name,
            status: this.form.status,
            typeId: this.form.typeId,
            fileSize: this.form.fileSize,
            role: role,
            conversationList: conversationList
          }
          this.refList.show ? this.addfile(code) : this.editfile(code)
        }
      })
    },
    /**
     * @method 新增文件
     * **/
    addfile(val) {
      api
        .POST('/doc/addDoc', val)
        .then(data => {
          if (data.code == 0) {
            this.$message.success(data.message)
            this.handleClose()
            this.fullscreenLoading = false
          }
        })
        .catch(() => {
          this.fullscreenLoading = false
        })
    },
    /**
     * @method 编辑文件
     * **/
    editfile(val) {
      val.id = this.form.id
      api
        .PUT('/doc/updateDoc', val)
        .then(data => {
          if (data.code == 0) {
            this.$message.success(data.message)
            this.handleClose()
            this.fullscreenLoading = false
          }
        })
        .catch(() => {
          this.fullscreenLoading = false
        })
    },
    /**
     * @method 增加访问权限
     * **/
    addjurisdiction() {
      this.form.role.push({ value: '' })
    },
    /**
     * @method 删除访问权限
     * **/
    deletjurisdiction(val) {
      this.form.role.splice(val, 1)
    },
    //会话下拉列表
    conversationGetDropList() {
      api.GET('conversation/getDropList').then(res => {
        if (res.code == 0) {
          this.conversationList = res.data
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.form_item_content {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.icon-a-zu903 {
  color: #f23f3a;
  margin-left: 10px;
  margin-right: 20px;
  cursor: pointer;
  font-size: 22px;
}
.icon-a-zu904 {
  cursor: pointer;
  font-size: 22px;
}
.el-icon-minus {
  margin-right: 16px;
}
</style>