<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showEditModal"
      :close-on-click-modal="false"
      :title="modalTitle"
      width="700px"
    >
      <div>
        <Form
          id="edit-form"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="80"
          inline
        >
          <Form-item label="模板类别" prop="pname" class="width-48">
            <el-input
              v-model="pname"
              readonly
              placeholder="请选择模板类别"
              @click.native="_selectZtree"
            />
            <input v-model.number="formObj.pid" name="pid" hidden>
          </Form-item>
          <Form-item label="名称" prop="alias" class="width-48">
            <el-input v-model="formObj.alias" name="alias" placeholder="请输入名称" @blur="_onKeyUp" />
          </Form-item>
          <Form-item label="备注" prop="remark" class="width-48">
            <el-input v-model="formObj.remark" name="remark" placeholder="请输入备注" />
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
        <label style="margin-bottom: 0">
          <Upload
            :action="action"
            :on-success="_handelsuccess"
            :before-upload="_beupload"
            :on-progress="_handelprogress"
            :on-format-error="_formatError"
            :data="dataObj"
            :with-credentials="true"
            :show-upload-list="false"
            :format="format"
          >
            <Button type="primary" :disabled="isDisable">导入文件</Button>
          </Upload>
        </label>
      </div>
    </el-dialog>
    <!--选择上级菜单tree-->
    <selectResourceTree ref="treeModal" @on-result-change="_treeData" />
    <!--选择图标-->
    <icons ref="iconsModal" @on-result-change="_iconsData" />
  </div>
</template>
<script>
/**
 * 添加编辑菜单表
 */
import { sysTemplate } from '../../api'
import global from '../../api/config'
import icons from '../../components/base/icons'
import selectResourceTree from './tree/selectEquipLocationTree'

export default {
  components: { selectResourceTree, icons },
  data() {
    return {
      id: '',
      modalTitle: '添加',
      formObj: {
        alias: '',
        classifyId: 0
      },
      ruleValidate: {
        code: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
        icon: [{ required: true, message: '图标不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        sort: [
          {
            required: true,
            message: '排序不能为空',
            trigger: 'blur',
            type: 'number'
          }
        ],
        uri: [{ required: true, message: '路径不能为空', trigger: 'blur' }]
      },
      isDisable: true,
      isLoad: false,
      pname: '',
      dataObj: {
        file: ''
      },
      showEditModal: false,
      footerList: [
        // { id: '', name: '取消', type: '' }
      ],
      typeList: [{ value: 0, name: 'PC 菜单' }, { value: 2, name: 'APP 菜单' }],
      statusList: [{ value: 1, name: '正常' }, { value: 0, name: '禁用' }]
    }
  },
  methods: {
    _onKeyUp() {
      if (this.formObj.alias === '' || this.pname === '') {
        this.isDisable = true
      } else {
        this.isDisable = false
        this.action =
          global.baseURL +
          '/v1/file_template/?alias=' +
          this.formObj.alias +
          '&classifyId=' +
          this.formObj.classifyId
      }
    },
    // modal
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '导入文件':
          this._ok()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _resultChange(result, msg) {
      if (result) {
        this.showEditModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          data.status = this.formObj.status
          data.type = this.formObj.type
          if (this.formObj.systemId) {
            data.systemId = this.formObj.systemId
          }
          this._save(data)
        } else {
          this.$message.error('表单验证失败')
          this._hideLoading()
        }
      })
    },
    // 添加、编辑保存
    _save: async function(data) {
      // 添加、编辑
      if (this.$string(this.id).isEmpty()) {
        const result = await sysTemplate.add(data)
        this._resultChange(result, '添加成功')
      } else if (
        this.$judgeClassify({ id: this.id, classifyId: this.formObj.pid })
      ) {
        const result = await sysTemplate.edit({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功')
      } else {
        this.$message.warning('上级菜单与菜单名不能重复，请重新选择~')
        this._hideLoading()
      }
    },
    _cancel() {
      this.showEditModal = false
    },
    _open(treeObj, formObj) {
      this.showEditModal = true
      this.$nextTick(() => {
        this.$refs.formObj.resetFields()
        this._hideLoading()
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.modalTitle = '添加类别'
          if (JSON.stringify(treeObj) !== '{}') {
            $('input[name=pid]').val(treeObj.id)
            this.formObj.pid = treeObj.id
            this.formObj.parentName = treeObj.name
          } else {
            this.formObj.pid = '0'
            this.formObj.parentName = ''
          }
        } else {
          this.id = formObj.id
          this.formObj = formObj
          this.modalTitle = '编辑菜单'
          this.$refs.systemModal._open(formObj.systemId)
        }
      })
    },
    // 选择系统返回
    _systemResult(data) {
      this.formObj.systemId = data
    },
    // 选择tree
    _selectZtree() {
      this.$refs.treeModal._open()
    },
    _treeData(result) {
      this.pname = ''
      console.log('-----result-----', result)
      if (result === undefined) {
        this.formObj.classifyId = '0'
        this.pname = ''
      } else {
        this.formObj.classifyId = result.id
        this.pname = result.name
      }
      // 判断必填项是否为空
      this._onKeyUp()
    },
    // 选择图标
    _selectIcon() {
      this.$refs.iconsModal._open()
    },
    _iconsData(data) {
      this.formObj.icon = data
    },

    _beupload(file) {
      this.dataObj.file = file.name
    },
    _handelprogress(event, file, fileList) {
      this.isLoad = true
    },
    _handelsuccess(response, file, fileList) {
      if (response.success) {
        this.isLoad = false
        this.$Message.success('上传成功！')
        this.showEditModal = false
        this.$emit('on-result-change')
      } else {
        this.isLoad = true
        this.$Message.error(response.msg)
      }
    },
    _formatError(file) {
      this.$Notice.error({
        title: '文件格式不正确',
        duration: 10,
        desc: '文件 ' + file.name + ' 格式不正确，请上传格式为 docx 的文件！'
      })
    }
  }
}
</script>
