<!-- 企业人才 -->
<template>
  <div class="content">
    <div v-loading.fullscreen.lock="loadingFull" />
    <div class="search_box flexS">
      <div v-for="(item, idx) in categoryList" :key="idx">
        <el-select v-model="params[item.mark]" :placeholder="item.name" class="select" @change="toSearch()" clearable
          @clear="toSearch()">
          <el-option v-for="item in item.children" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </div>
      <el-input v-model="params.search_name" clearable placeholder="请输入姓名" prefix-icon="el-icon-search"
        @keyup.enter.native="toSearch()" @clear="toSearch()" />
      <el-button type="primary" icon="el-icon-search" :loading="loadingFull" @click="toSearch()">搜索</el-button>
      <el-button @click="handleEdit(false)" type="primary" style="margin-right:24px;">添加</el-button>
      <el-upload class="upload-demo" action="" :http-request="uploadFile" :multiple="false" :show-file-list="false">
        <el-button type="primary">导入</el-button>
      </el-upload>
    </div>
    <div class="table_box">
      <el-table ref="list" :data="listData" align="center" :header-cell-style="{ background: '#f8fbfc' }"
        class="tableBorder" border stripe>
        <el-table-column prop="name" label="姓名" align="center" />
        <el-table-column prop="company_id" label="所属企业" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.company && row.company.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="industry" label="行业" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.industry && row.industry.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="degree" label="学历" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.degree && row.degree.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="人才类型" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.type && row.type.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280">
          <template slot-scope="{row}">
            <el-button type="text" size="mini" @click="handleEdit(true, row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer :title="!isEdit ? '添加人才信息' : '编辑人才信息'" :visible.sync="dialogVisible" width="35%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="照片：">
          <el-upload ref="upload" action="" :show-file-list="false" :http-request="uploadImg">
            <div v-if="ruleForm.img">
              <img :src="ruleForm.img" class="thumbUrl" style="width: 100px;height: 137px;">
            </div>
            <div v-else>
              <el-button size="mini">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                (建议尺寸画布600*480，大小50K)
              </div>
            </div>
          </el-upload>

        </el-form-item>
        <el-form-item label="所属企业:" prop="company_id">
          <el-select v-model="ruleForm.company_id" placeholder="请选择所属企业">
            <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-for="(item, i) in categoryList" :key="i" :label="item.name" :prop="item.mark">
          <el-select v-model="ruleForm[item.mark]" :placeholder="'请选择' + item.name" :ref="'template_' + i"
            :style="{ width: '300px' }" filterable clearableruleFormruleForm>
            <el-option v-for="(temp, idx) in item.children" :key="idx" :label="temp.name" :value="temp.id">
              <span style="float: left" class="span-style">{{ temp.name }}</span>
              <!-- <span style="float: right" class="span-style-delete" @click.stop="deleteItem(temp)">
                <i class="el-icon-delete" /></span> -->
              <span style="float: right" class="span-style" @click.stop="editItem(item.id, true, temp, i)">
                <i class="el-icon-edit-outline" />
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否研发机构" prop="is_research" required>
          <el-radio-group v-model="ruleForm.is_research">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介:" prop="introduction" required>
          <textarea name="" id="" cols="30" rows="10" v-model="ruleForm.introduction" placeholder="请输入人才简介" />
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">{{ !isEdit ? '确 定' : '保存' }}</el-button>
        </el-form-item>
      </el-form>

    </el-drawer>
    <div class="paging_box">
      <pagination :total="listDataTotal" :limit="params.page_size" :page="params.page_index"
        @pagination="changePagination" @update:limit="changePagination" />
    </div>
  </div>
</template>
<script>
import { talentList, addTalent, editTalent, deleteTalent, importTalent, talentCategory, companyAll } from '@/api/company'
import { uploadFile } from '@/api/upload.js'
import { addCategory, editCategory, deleteCategory } from '@/api/category'
export default {
  data() {
    return {
      isEdit: false,
      categoryList: [],
      category: [],
      dialogVisible: false,
      loadingFull: false,
      listData: [],
      listDataTotal: 0,
      id: '',
      options1: [],
      options2: [],
      options3: [],
      companyList: [],
      ruleForm: {
        name: '',
        company_id: '',
        img: '',
        industry: '',
        degree: '',
        introduction: '',
        type: '',
        is_research: ''
      },
      params: {
        page_index: 1,
        page_size: 10,
        search_name: '',
        search_company: '',
        type: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        img: [
          { required: true, message: '请上传照片', trigger: 'blur' }
        ],
        company_id: [
          { required: true, message: '请选择所属企业', trigger: 'change' }
        ],
        industry: [
          { required: true, message: '请选择行业类型', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择人才类型', trigger: 'change' }
        ],
        degree: [
          { required: true, message: '请选择人才学历', trigger: 'change' }
        ],
        is_research: [
          { required: true, message: '请选择是否研发机构', trigger: 'change' }
        ],
        sort: [
          { required: true, message: '请输入排名', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getList()
    this.getCategory()
    this.getCompany()
  },
  methods: {
    // 修改类型
    editItem(fid, isEdit, info, idx) {
      this.addItem(fid, isEdit, info, idx)
    },
    // 添加/修改类型
    addItem(fid, isEdit, info, idx) {
      if (info && info != null && !isEdit) {
        this.$message.error('无可编辑内容')
        return
      }
      let val = ''
      if (info) {
        const index = this.categoryList[idx].children.findIndex((e) => e.id === info.id)
        const obj = this.categoryList[idx].children[index]
        val = obj.name
      }
      this.$prompt(' 请输入新的类型名称 ', isEdit ? '编辑' : '添加', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: val
      }).then(async ({ value }) => {
        if (!value || value === '') {
          this.$message.error('类型名称不能为空!')
        } else {
          const http = isEdit ? editCategory : addCategory
          const data = isEdit ? { fid, id: info.id, name: value } : { fid, name: value }
          http(data).then(res => {
            if (res.code === 200) {
              this.$message.success(isEdit ? '修改类型成功' : '添加类型成功')
              this.getCategory()
            } else {
              this.$message.success(res.msg || isEdit ? '修改类型失败' : '添加类型失败')
            }
          })
        }
      })
    },
    // 删除类型
    deleteItem(info) {
      this.$confirm("确定要删除" + "' " + info.name + " '" + "吗？", "删除", {
        type: 'warning'
      })
        .then(() => {
          // 本地静态删除
          deleteCategory({ id: info.id }).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.getCategory()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
        })
        .catch(() => { });
    },
    // 下拉时显示底下的新增按钮
    visibleChange(visible, refName, fid) {
      if (visible) {
        const ref = this.$refs[refName][0];
        let product = ref.$refs.popper;
        if (product.$el) product = product.$el;
        if (
          !Array.from(product.children).some(
            (v) => v.className === "el-template-menu__list"
          )
        ) {
          const el = document.createElement("ul");
          el.className = "el-template-menu__list";
          el.style =
            "border-top:2px solid rgb(219 225 241); padding:0; color:rgb(64 158 255);font-size: 13px";
          el.innerHTML = `<li class="el-cascader-node text-center" style="height:37px;line-height: 50px;margin-left:10px;">
            <span class="el-cascader-node__label"><i class="font-blue el-icon-plus"></i> 新增</span>
            </li>`;
          product.appendChild(el);
          // 新增按钮点击事件
          el.onclick = () => {
            this.addItem(fid, 0);
          };
        }
      }
    },
    // 获取企业列表
    async getCompany() {
      try {
        const res = await companyAll()
        const { msg, code, data } = res
        if (code === 200) {
          this.companyList = data
        } else {
          this.$message.error(msg)
        }
      } catch (e) {
        console.log(`获取列表失败:${e}`)
      }
    },
    // 获取列表
    async getCategory() {
      try {
        const res = await talentCategory()
        const { message, code, data } = res
        if (code === 200) {
          this.categoryList = data
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取列表失败:${e}`)
      }
    },
    // 轮播图上传
    uploadImg(params) {
      this.thumbLoad = true
      const file = params.file
      const imgType = ['image/png', 'image/jpg', 'image/jpeg']
      if (imgType.indexOf(file.type) === -1) {
        this.$message.warning('上传图片格式必须为: png或jpg格式')
        return false
      }
      const formData = new FormData()
      formData.append('file', file)
      formData.append('dir', 'image/talent')
      uploadFile(formData)
        .then(res => {
          this.thumbLoad = false
          try {
            const { message, code, data } = res
            if (code === 200) {
              // 域名/storage/ 拼接
              this.ruleForm.img = 'http://api.xysyszhd.dev.xmnk.cn/storage/' + data
            } else {
              this.$message.error(message)
            }
          } catch (e) {
            console.log(`上传轮播图失败: ${e}`)
          }
        })
        .catch(() => {
          this.thumbLoad = false
        })
    },
    // 搜索
    toSearch() {
      this.params.page_index = 1
      this.getList()
    },
    // 导入
    uploadFile(params) {
      const file = params.file
      var formData = new FormData()
      formData.append('file', file)
      const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
      console.log(file.name, 'file')
      if (!isExcel) {
        this.$message.error('仅支持上传 .xlsx 或 .xls 格式的文件!')
        return
      }
      importTalent(formData).then(res => {
        if (res.code === 200) {
          this.$message.success('导入成功！')
          this.getList()
        } else {
          this.$message.error(res.message || '导入失败！')
        }
      })
    },
    reset() {
      this.ruleForm = {
        name: '',
        company_id: '',
        img: '',
        industry: '',
        degree: '',
        introduction: '',
        type: '',
        is_research: ''
      }
    },
    // 编辑或者添加人才信息
    handleEdit(isEdit, row) {
      this.dialogVisible = true
      this.isEdit = isEdit
      if (!isEdit) { // 添加
        this.reset()
      } else { // 编辑
        this.id = row.id
        this.ruleForm = {
          name: row.name,
          company_id: row.company_id,
          img: row.img,
          industry: row.industry && row.industry.id,
          degree: row.degree && row.degree.id,
          introduction: row.introduction,
          type: row.type && row.type.id,
          is_research: row.is_research
        }
      }
    },
    // 获取列表
    async getList() {
      this.loadingFull = true
      try {
        const res = await talentList(this.params)
        const { message, code, data } = res
        if (code === 200) {
          const { list, total } = data
          this.listData = list
          this.listDataTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取列表失败:${e}`)
        this.loadingFull = false
      }
      this.loadingFull = false
    },
    // 添加/编辑事件
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const http = !this.isEdit ? addTalent : editTalent
          const { name, company_id, img, industry, degree, introduction, type, is_research } = this.ruleForm
          const data = !this.isEdit ? this.ruleForm : { name, company_id, img, industry, degree, introduction, type, is_research, id: this.id }
          http(data).then(res => {
            if (res.code === 200) {
              this.$message.success(!this.isEdit ? '添加成功!' : '修改成功！')
              this.getList()
              this.dialogVisible = false
            } else {
              this.$message.error(!this.isEdit ? '添加失败!' : '修改失败！')
              this.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除确认
    handleDelete(row) {
      const { id } = row
      this.$confirm('确认要删除该人才信息吗?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteEvent(id)
      })
    },
    // 删除事件
    async deleteEvent(id) {
      const res = await deleteTalent({ id })
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success('删除成功！')
          this.getList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.params.page_size = limit
      this.params.page_index = page
      this.getList()
    }
  }

}
</script>
<style lang="scss" scoped>
.el-input,
textarea {
  width: 350px;
}
</style>