<template>
  <div>
    <el-dialog v-loading = "loading" :visible.sync="visible" :append-to-body="appendToBody" :before-close="beforeClose" title="审批" width="1200px" destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px" label-position="right" type="flex">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item prop="STATUS" label="是否通过: ">
              <el-select v-model="form.STATUS" filterable style="width: 300px" placeholder="请选择" @change="clearInfo">
                <el-option label="是" value="1"/>
                <el-option label="否" value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.STATUS === '1' && !form.STEP" prop="APPOINT_DEPARTMENT_ID" label="指定监管部门:">
              <Treeselect
                :options="departmentTree"
                :normalizer="normalizer"
                v-model="form.APPOINT_DEPARTMENT_ID"
                placeholder="请选择部门"
                no-options-text="暂无数据"
                no-children-text="暂无数据"
                style="width: 300px"
                @select="getPeopleList($event)"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="form.STATUS === '0'" :span="12">
            <el-form-item v-if="form.STATUS === '0'" prop="OPINION" label="打回原因:">
              <el-input v-model="form.OPINION" :rows="2" type="textarea" placeholder="填写审批意见"/>
            </el-form-item>
          </el-col>
          <el-col v-if="form.STATUS === '1' && !form.STEP " :span="12">
            <el-form-item v-if="form.STATUS === '1'" prop="APPOINT_USER_ID" label="指定监管部门审批人:">
              <el-select v-model="form.user" style="width: 300px" placeholder="请选择" @change="chooseUser">
                <el-option v-for="item in peopleList" :key="item.USER_ID" :value="JSON.stringify(item)" :label="item.NAME"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.STATUS === '1' && !form.STEP " :span="12">
            <el-form-item v-if="form.STATUS === '1'" prop="LIMIT_END_TIME" label="指定培训有效截至时间:">
              <el-date-picker v-model="form.LIMIT_END_TIME" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" style="width:300px "/>
            </el-form-item>
          </el-col>
          <el-col v-if="form.STATUS === '1' && form.TYPE === '2'" :span="12">
            <el-form-item label="承诺书:" prop="APPOINT_ANNEX">
              <upload-file
                :file-list.sync="form.APPOINT_ANNEX"
                :multiple="false"
                :accept="'.pdf,.jpg,.png,doc,docx'"
                :limit="20"
                :size="1024"
                :upload-type="1"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">关 闭</el-button>
        <el-button type="primary" @click="sendMessage('1')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import vueQr from 'vue-qr'
import Treeselect from '@riophae/vue-treeselect'
import { requestFN } from '@/utils/request'
import uploadFile from '../../../util/uploadFile/index.vue'
import { upload } from '@/utils/upload'

export default {
  components: { uploadFile, Treeselect, vueQr },
  props: {
    appendToBody: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      form: {
        STATUS: null,
        APPOINT_CORP_ID: '',
        APPOINT_CORP_NAME: '',
        APPOINT_DEPARTMENT_ID: null,
        APPOINT_DEPARTMENT_NAME: '',
        APPOINT_USER_ID: null,
        APPOINT_USER_NAME: '',
        APPOINT_ANNEX: null,
        OPINION: '',
        STEP: false,
        LIMIT_END_TIME: '',
        user: '',
        tm: new Date().getTime(),
        list: [],
        isShow: true,
        info: {},
        TYPE: null
      },
      rules: {
        STATUS: [
          { required: true, message: '请选择是否通过', trigger: 'change' }
        ],
        APPOINT_DEPARTMENT_ID: [
          { required: true, message: '请选择指定监管部门', trigger: 'change' }
        ],
        APPOINT_USER_ID: [
          { required: true, message: '请选择指定监管部门审批人', trigger: 'change' }
        ],
        OPINION: [
          { required: true, message: '请填写打回原因', trigger: 'change' }
        ],
        LIMIT_END_TIME: [
          { required: true, message: '请选择指定培训有效截至时间', trigger: 'change' }
        ]
      },
      heirloom: {},

      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.nodes
        }
      },

      departmentTree: [],
      peopleList: []
    }
  },
  methods: {
    async init(e) {
      this.loading = true
      this.visible = true
      this.heirloom = JSON.stringify(e)
      this.form.list = JSON.stringify(e)
      // 确定是不是最后一步，是：ture，否：false
      this.form.STEP = (e[0].FLOWS_STEP === 2) || (e[0].FLOWS_STEP === 1 && e[0].FLOWS_TYPE === '2')
      this.form.TYEP = e[0].FLOWS_TYPE
      this.getDepartmentTree()
      this.loading = false
    },
    sendMessage(e) {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          this.$message.error('请填写完整信息')
        } else {
          if (this.form.TYPE !== '2') {
            this.loading = true
            requestFN('/xgf/user/approveMax', this.form)
              .then((data) => {
                this.$message.success('推送成功')
                this.visible = false
                this.$emit('refresh', '')
                this.handleClose()
                this.loading = false
              })
              .catch((e) => {
                console.log(e)
              })
          } else {
            const formData = new FormData()
            this.form.chengNuoFlag = '1'
            Object.keys(this.form).map(key => {
              formData.append(key, this.form[key])
            })
            if (this.form.APPOINT_ANNEX) {
              for (let i = 0; i < this.form.APPOINT_ANNEX.length; i++) {
                formData.append('weiTuoShu', this.form.APPOINT_ANNEX[i].raw)
              }
            }
            this.loading = true
            upload('/xgf/user/approveMax', formData)
              .then((data) => {
                this.$message.success('推送成功')
                this.visible = false
                this.$emit('refresh', '')
                this.handleClose()
                this.loading = false
              })
              .catch((e) => {
                console.log(e)
              })
          }
        }
      })
    },
    getDepartmentTree() {
      return new Promise(resolve => {
        requestFN(
          '/department/listTree',
          {}
        ).then((data) => {
          this.departmentTree = this.removeEmptyChildren(JSON.parse(data.zTreeNodes))
          resolve(true)
        }).catch((e) => {
        })
      })
    },
    getCorpDepartmentTree() {
      return new Promise(resolve => {
        requestFN(
          '/openApi/corpDepartment/listTree',
          {}
        ).then((data) => {
          this.departmentTree = this.removeEmptyChildren(JSON.parse(data.zTreeNodes))
          resolve(true)
        }).catch((e) => {
        })
      })
    },
    getPeopleList(e) {
      this.form.APPOINT_DEPARTMENT_NAME = e.name
      requestFN(
        '/user/listAll',
        {
          DEPARTMENT_ID: e.id
        }
      ).then((data) => {
        this.peopleList = data.userList
        this.form.user = ''
      }).catch((e) => {
        console.log(e)
      })
    },
    chooseUser(e) {
      const entity = JSON.parse(e)
      this.form.APPOINT_USER_ID = entity.USER_ID
      this.form.APPOINT_USER_NAME = entity.NAME
    },

    handleClose() {
      this.form = {
        STATUS: '',
        APPOINT_DEPARTMENT_ID: null,
        APPOINT_DEPARTMENT_NAME: '',
        APPOINT_USER_ID: '',
        APPOINT_USER_NAME: '',
        OPINION: '',
        user: '',
        list: [],
        tm: new Date().getTime()
      }
      this.visible = false
    },
    beforeClose() {
      this.visible = false
      this.form = {
        STATUS: '',
        APPOINT_DEPARTMENT_ID: null,
        APPOINT_DEPARTMENT_NAME: '',
        APPOINT_USER_ID: '',
        APPOINT_USER_NAME: '',
        OPINION: '',
        user: '',
        list: [],
        tm: new Date().getTime()
      }
    },
    clearInfo() {
      this.form.APPOINT_DEPARTMENT_ID = null
      this.form.APPOINT_DEPARTMENT_NAME = ''
      this.form.APPOINT_USER_ID = null
      this.form.APPOINT_USER_NAME = ''
      this.form.OPINION = ''
      this.form.user = ''
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
