<template>
  <div>
    <Modal v-model="showEditModal" v-drag :mask-closable="false" width="800">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Form
          id="edit-form"
          ref="formObj"
          inline
          :model="formObj"
          :rules="ruleValidate"
          :label-width="88"
        >
          <Form-item label="培训名称" prop="name" class="width-48">
            <Input v-model="formObj.name" name="name" placeholder="请输入培训名称" /></Input>
          </Form-item>
          <Form-item label="培训类型" prop="type" class="width-48">
            <Select v-model="formObj.type" name="type" filterable clearable>
              <Option v-for="item in typeList" :key="item.id" :value="item.id">
                {{ item.name }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="负责人" prop="charger" class="width-48">
            <Select
              v-model="formObj.charger"
              name="charger"
              clearable
              :label-in-value="true"
              @on-change="_chargerChange"
            >
              <Option v-for="item in userList" :key="item.id" :value="item.id">
                {{ item.name }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="培训人员" prop="staffIds" class="width-48">
            <Select
              v-model="trainList"
              name="staffIds"
              filterable
              multiple
              :label-in-value="true"
              @on-change="_trainChange"
            >
              <Option v-for="item in userList" :key="item.id" :value="item.id">
                {{ item.name }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="培训开始日期" prop="beginDate" class="width-48">
            <Date-picker
              v-model="formObj.beginDate"
              name="beginDate"
              type="date"
              placeholder="培训开始日期"
              format="yyyy-MM-dd"
              style="width: 100%;"
              :editable="false"
            />
          </Form-item>
          <Form-item label="培训结束日期" prop="endDate" class="width-48">
            <Date-picker
              v-model="formObj.endDate"
              name="endDate"
              type="date"
              placeholder="培训结束日期"
              format="yyyy-MM-dd"
              style="width: 100%;"
              :editable="false"
            />
          </Form-item>
          <Form-item label="考核办法" prop="assessmentMethod" class="width-48">
            <Select v-model="formObj.assessmentMethod" filterable clearable>
              <Option v-for="item in methodList" :key="item.id" :value="item.id">
                {{ item.name }}
              </Option>
            </Select>
          </Form-item>
          <Form-item label="培训内容" prop="trainContent" class="width-48">
            <!--            <Editor ref="editorModal" v-model="formObj.trainContent" @on-result-change="_editorData" />-->
            <Input v-model="formObj.trainContent" placeholder="请输入培训内容" /></Input>
          </Form-item>
          <Form-item label="培训目标" prop="trainAim" class="width-48">
            <Input v-model="formObj.trainAim" placeholder="请输入培训目标" /></Input>
          </Form-item>
          <Form-item label="备注" prop="remark" class="width-48">
            <Input v-model="formObj.remark" placeholder="请输入备注" /></Input>
          </Form-item>
          <input v-model="formObj.chargerName" name="chargerName" type="hidden">
          <input v-model="formObj.staffNames" name="staffNames" type="hidden">
        </Form>
      </div>
      <div slot="footer" class="btn-width">
        <Button type="success" style="margin-left: 8px" @click="_cancel">
          取消
        </Button>
        <Button type="success" style="margin-left: 8px" @click="_draft">
          草稿
        </Button>
        <Button type="primary" @click="_ok">
          提交
        </Button>
      </div>
    </Modal>
  </div>
</template>
<script>
/**
 * 添加编辑人员管理-人员培训计划
 */
import global from '../../../api/config'
import { dict, staffInfo } from '../../../api'
import staffTrainPlan from '../../../api/staff/staffTrainPlan'
export default {
  components: {},
  data() {
    return {
      id: '',
      modalTitle: '',
      formObj: {
        name: '',
        type: '',
        charger: '',
        chargerName: '',
        staffIds: '',
        staffNames: '',
        beginDate: '',
        endDate: '',
        assessmentMethod: '', //
        trainContent: '', //
        trainAim: '',
        remark: '' //
      },
      ruleValidate: {},
      showEditModal: false,
      userList: [],
      trainList: [],
      methodList: [], // 考核方法
      typeList: [], // 培训类型
      files: [],
      isLoad: true,
      fileAction: '',
      fileObj: {
        file: ''
      },
      filePath: '',
      trainPlanIdTemp: '',
      fileName: ''
    }
  },
  mounted() {},
  methods: {
    _getTypeList: async function() {
      const result = await dict.getItem('人员培训类型')
      if (result) {
        this.typeList = result
      }
    },
    _getUserList: async function() {
      const result = await staffInfo.list({ status: 1 })
      if (result) {
        this.userList = result
      }
    },
    _getMethodList: async function() {
      const result = await dict.getItem('人员考核办法')
      if (result) {
        this.methodList = result
      }
    },
    _editorData(html, text) {
      // 培训内容
      this.formObj.trainContent = html
    },
    _resultChange(msg) {
      this.formObj = {}
      this.showEditModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          data.charger = this.formObj.charger
          data.staffIds = this.formObj.staffIds
          data.assessmentMethod = this.formObj.assessmentMethod
          data.trainContent = this.formObj.trainContent
          data.trainAim = this.formObj.trainAim
          data.remark = this.formObj.remark
          if (this.$string(this.id).isEmpty()) {
            data.id = this.trainPlanIdTemp // 新增数据的同时传数据id
            console.log('save------', data)
            this._commit(data)
            // 新增
            // this.$store
            //   .dispatch(
            //     'LmsStaffTrainPlan/add',
            //     this.$serializeFormSearch(data)
            //   )
            //   .then(() => {
            //     this._resultChange('添加成功!')
            //   })
          } else {
            this._editDraft({
              id: this.formObj.id,
              obj: this.$serializeFormSearch(data)
            })
            // 编辑
            // this.$store
            //   .dispatch('LmsStaffTrainPlan/edit', {
            //     id: this.formObj.id,
            //     obj: this.$serializeFormSearch(data)
            //   })
            //   .then(() => {
            //     this._resultChange('编辑成功!')
            //   })
          }
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },
    _draft() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          data.charger = this.formObj.charger
          data.staffIds = this.formObj.staffIds
          data.assessmentMethod = this.formObj.assessmentMethod
          data.trainContent = this.formObj.trainContent
          data.trainAim = this.formObj.trainAim
          data.remark = this.formObj.remark
          if (this.$string(this.id).isEmpty()) {
            data.id = this.trainPlanIdTemp // 新增数据的同时传数据id
            console.log('_draft--------------', data)
            this._saveDraft(data)
            // 保存草稿
            // this.$store
            //   .dispatch(
            //     'LmsStaffTrainPlan/draft',
            //     this.$serializeFormSearch(data)
            //   )
            //   .then(() => {
            //     this._resultChange('添加成功!')
            //   })
          } else {
            // 编辑
            // this.$store
            //   .dispatch('LmsStaffTrainPlan/edit', {
            //     id: this.formObj.id,
            //     obj: this.$serializeFormSearch(data)
            //   })
            //   .then(() => {
            //     this._resultChange('编辑成功!')
            //   })

            this._editDraft({
              id: this.formObj.id,
              obj: this.$serializeFormSearch(data)
            })
          }
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },

    _saveDraft: async function(data) {
      const result = await staffTrainPlan.add(data)
      if (result) {
        this._resultChange('添加成功!')
      }
    },
    _commit: async function(data) {
      const result = await staffTrainPlan.commit(data)
      if (result) {
        this._resultChange('提交成功!')
      }
    },
    _editDraft: async function(data) {
      const result = await staffTrainPlan.edit(data)
      if (result) {
        this.showEditModal = false
        this.$Message.success('编辑成功')
        this.$emit('on-result-change')
      }
    },
    _cancel() {
      this.showEditModal = false
    },
    _open(formObj, msg) {
      this.formObj = {}
      this._getUserList()
      this._getTypeList()
      this._getMethodList()
      this.showEditModal = true
      this.$refs.formObj.resetFields()
      if (!msg) {
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.formObj = {}
          this.modalTitle = '添加人员培训计划'
          this.trainList = []
          this.files = []
          // 获取附件信息
          this._getFiles()
        } else {
          this.id = formObj.id
          this.formObj = formObj
          this.formObj.trainContent = formObj.trainContent
          this.formObj.staffIds = formObj.staffIds
          this.formObj.staffNames = formObj.staffNames
          this.modalTitle = '编辑人员培训计划'
          if (this.formObj.beginDate === undefined) {
            this.formObj.beginDate = ''
          } else {
            this.formObj.beginDate = this.$dateformat(
              formObj.beginDate,
              'yyyy-mm-dd'
            )
          }
          if (this.formObj.endDate === undefined) {
            this.formObj.endDate = ''
          } else {
            this.formObj.endDate = this.$dateformat(
              formObj.endDate,
              'yyyy-mm-dd'
            )
          }
          // 培训人员回显
          this.trainList = formObj.staffIds ? formObj.staffIds.split(',') : []
        }
      } else {
        // 复制
        this.formObj = formObj
        this.formObj.name = formObj.name ? formObj.name : ''
        this.formObj.type = formObj.type ? formObj.type : ''
        this.formObj.charger = formObj.charger ? formObj.charger : ''
        this.formObj.chargerName = formObj.chargerName
          ? formObj.chargerName
          : ''
        this.formObj.staffIds = formObj.staffIds ? formObj.staffIds : ''
        this.formObj.staffNames = formObj.staffNames ? formObj.staffNames : ''
        this.formObj.beginDate = formObj.beginDate
          ? this.$dateformat(formObj.beginDate, 'yyyy-mm-dd')
          : ''
        this.formObj.endDate = formObj.endDate
          ? this.$dateformat(formObj.endDate, 'yyyy-mm-dd')
          : ''
        this.formObj.trainContent = formObj.trainContent
          ? formObj.trainContent
          : ''
        this.formObj.trainAim = formObj.trainAim ? formObj.trainAim : ''
        this.formObj.remark = formObj.remark ? formObj.remark : ''
        this.id = ''
        this.formObj.id = ''
        this.modalTitle = '添加人员培训计划'
        // 培训人员回显
        this.trainList = formObj.staffIds ? formObj.staffIds.split(',') : []
        this.files = [] // 获取附件信息
        // 获取附件信息
        this._getFiles()
      }
    },
    _chargerChange(obj) {
      this.formObj.chargerName = obj.label
      this.formObj.charger = obj.value
    },
    _trainChange(obj) {
      let ids = ''
      let names = ''
      obj.forEach(function(item) {
        ids = ids + item.value + ','
        names = names + item.label + ','
      })
      this.formObj.staffIds = ids.substring(0, ids.length - 1)
      this.formObj.staffNames = names.substring(0, names.length - 1)
    },
    // 只是为了获取id
    _getFiles: async function() {
      const result = await staffTrainPlan.getTemp()
      if (result) {
        this.trainPlanIdTemp = result.id
        this.fileAction =
          global.baseURL +
          '/res/v1/staff_train_plan_attachment/uploadFile?id=' +
          this.trainPlanIdTemp
      }
      // this.$store.dispatch('LmsStaffTrainPlan/temp').then(() => {
      //   const result = this.$store.state.LmsStaffTrainPlan.list
      //   this.trainPlanIdTemp = result.id
      //   this.fileAction =
      //     global.baseURL +
      //     '/res/v1/staff_train_plan_attachment/uploadFile?id=' +
      //     this.trainPlanIdTemp
      // })
    },
    // 获取所有附件
    _getFilesAll(trainPlanId) {
      // this.$store
      //   .dispatch('LmsStaffTrainPlanAttachment/list', {
      //     trainPlanId: trainPlanId
      //   })
      //   .then(() => {
      //     const result = this.$store.state.LmsStaffTrainPlanAttachment.list
      //     this.files = result
      //   })
    },
    /** ******************* 附件上传**********************/
    _handleBefore(file) {
      this.isLoad = false
      this.fileObj.file = file.name
    },
    _handleSuccess(response, file, fileList) {
      if (response.success) {
        this.$Message.success('上传成功！')
        this.files.push(response.data)
        this.isLoad = true
      } else {
        this.$Message.error('上传失败！')
        this.isLoad = true
      }
    },
    _handleView(data) {
      this.fileName = data.fileName
      if (
        this.fileName.indexOf('jpg') > -1 ||
        this.fileName.indexOf('png') > -1 ||
        this.fileName.indexOf('jpeg') > -1
      ) {
        const images = [
          global.baseURL +
            '/res/v1/staff_train_plan_attachment/download/' +
            data.id
        ]
        this.$refs.ViewImage.images = images
        this.$refs.ViewImage._open(images)
      } else {
        this.$Message.warning({
          content: '非图片文件无法查看，请下载查看',
          duration: 3
        })
      }
    },
    _downloadFile(file) {
      // 下载文件
      this.$Modal.confirm({
        title: '提示',
        content: '确定要下载？',
        onOk: () => {
          const url =
            global.baseURL +
            '/res/v1/staff_train_plan_attachment/download/' +
            file.id
          window.open(url)
        }
      })
    },
    _handleRemove(file) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除文件？',
        onOk: () => {
          // this.$store
          //   .dispatch('LmsStaffTrainPlanAttachment/deleteFileById', file.id)
          //   .then(() => {
          //     if (this.$store.state.LmsStaffTrainPlanAttachment.success) {
          //       this.files.splice(this.files.indexOf(file), 1)
          //       this.$Message.success('删除成功！')
          //     }
          //   })
        }
      })
    }
    /** ******************* 附件上传**********************/
  }
}
</script>
