<template>
  <div>
    <el-dialog
      :before-close="handleClose"
      :close-on-click-modal="false"
      :title="title + '资料信息'"
      :visible="visible"
      custom-class="bbsl-location-dialog"
      width="50%"
    >
      <div>
        <el-form
          ref="formInfo"
          :model="this.parameter"
          :rules="rules"
          label-position="top"
          label-width="150px"
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="资料名称" prop="title">
                <el-input
                  v-model="parameter.title"
                  clearable
                  placeholder="请输入资料名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="资料分类：">
                <el-cascader
                  v-model="parameter.typeId"
                  :options="MaterialDataType"
                  :props="{value: 'id', label: 'name', checkStrictly: true}"
                  clearable
                  filterable
                  style="width: 100%"
                  @change="handleChange"
                >
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关键词" prop="keyword">
                <el-input
                  v-model="parameter.keyword"
                  clearable
                  placeholder="请输入关键词"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="下载授权" prop="accessControlType">
                <el-radio
                  v-for="(item, index) in accessControlTypeList"
                  :key="index"
                  v-model="parameter.examMaterialVo.accessControlType"
                  :label="item.value"
                  @change="clearData()"
                >
                  {{ item.name }}
                </el-radio>
              </el-form-item>
            </el-col>
            <el-col
              v-if="parameter.examMaterialVo.accessControlType == 2"
              :span="24"
            >
              <el-form-item label="已选中组织" prop="">
                <el-select
                  v-model="OrgsListIds"
                  multiple
                  placeholder="请选择组织"
                  style="width:80%"
                  @change="selectOne"
                  v-on:click.native="selectOrgs"
                >
                  <el-option
                    v-for="(item, index) in OrgsLists"
                    :key="index"
                    :label="item.accessControlName"
                    :value="item.accessControlId"
                  >
                  </el-option>
                </el-select>
                <el-button @click="clear()">重 置</el-button>
              </el-form-item>
            </el-col>
            <el-col
              v-if="parameter.examMaterialVo.accessControlType == 3"
              :span="24"
            >
              <el-form-item label="已选中用户" prop="">
                <el-select
                  v-model="UsersListIds"
                  multiple
                  placeholder="请选择用户"
                  style="width:80%"
                  @change="selectTwo"
                  v-on:click.native="selectUsers"
                >
                  <el-option
                    v-for="(item, index) in UsersList"
                    :key="index"
                    :label="item.accessControlName"
                    :value="item.accessControlId"
                  >
                  </el-option>
                </el-select>
                <el-button @click="clear()">重 置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="资料简介：" prop="memo">
                <el-input
                  v-model="parameter.memo"
                  :rows="2"
                  clearable
                  placeholder="请输入资料简介"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="附件：">
                <el-upload
                  :accept="accept"
                  :action="uploadUrl"
                  :before-remove="beforeRemove"
                  :before-upload="beforeUpload"
                  :data="{bizCode: 'Accessory', bizType: '1', bizId: ''}"
                  :file-list="fileList"
                  :headers="header"
                  :on-success="uploadSuccess"
                  name="files"
                >
                  <el-button icon="el-icon-upload" size="mini" type="success"
                    >上传
                  </el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSave">确认</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 组织 -->
    <SelectOrganize ref="OrgsModal"></SelectOrganize>

    <!-- 用户 -->
    <SelectUser ref="UsersModal"></SelectUser>
  </div>
</template>

<script>
import dictUtils from '@/components/dict/DictSelectUtils.js'
import zlxxMenu from '@/api/examination/zlxxMenu.js'
import SelectOrganize from './SelectOrganize.vue'
import SelectUser from './SelectUser.vue'
import {mapState} from 'vuex'

export default {
  name: 'zlxxMenuDialog',
  components: {
    SelectOrganize,
    SelectUser
  },
  data() {
    return {
      // 附件上传
      fileList: [],
      uploadUrl: window.context.portal + '/file/v1/fileUpload', // 服务器上传地址
      accept:
        '.bmp,.jpg,.png,.tif,.gif,.pcx,.tga,.exif,.fpx,.svg,.psd,.cdr,.pcd,.dxf,.ufo,.eps,.ai,.raw,.WMF,.webp,.avif,.apng,.xls,.docx,.docm,.doc,.dotx,.pptx,.pptm,.ppt,.pdf,.xps,.potx,.txt,.xls,.xlsx,.xps,.zip,.rar,.7z',
      previewUrl: window.context.portal + '/file/v1/downloadFile?fileId=',
      //
      title: '新增',
      visible: false,
      parameter: {
        examFiles: [],
        examMaterialVo: {
          accessControlList: [],
          accessControlType: '',
          authType: '',
          typeId: ''
        },
        keyword: '',
        memo: '',
        title: '',
        typeId: ''
      },
      MaterialDataType: [],
      rules: {
        title: [
          {
            required: true,
            message: '请输入资料名称',
            trigger: 'blur'
          }
        ],
        typeId: [
          {
            required: true,
            message: '请选择资料分类',
            trigger: 'blur'
          }
        ],
        keyword: [
          {
            required: true,
            message: '请输入关键词',
            trigger: 'blur'
          }
        ]
      },
      materialTypeList: [],
      accessControlTypeList: [],
      // 组织列表
      OrgsLists: [],
      OrgsListIds: [],
      // 用户列表
      UsersListIds: [],
      UsersList: []
    }
  },
  created() {
    this.accessControlTypeList = dictUtils.getDictItemsFromCache('qxsklx')
  },
  mounted() {
    // ref绑定自定义事件
    this.$refs.OrgsModal.$on('getOrgs', this.getOrg)
    this.$refs.UsersModal.$on('getUser', this.getUser)
  },
  computed: mapState({
    header: state => {
      return {
        Authorization: `Bearer ${state.login.currentUser.token}`
      }
    }
  }),
  methods: {
    // 附件上传
    uploadSuccess(res) {
      if (res) {
        // this.parameter.examFiles = []
        this.parameter.examFiles.push({
          fileName: res.fileName,
          id: res.fileId,
          fileUrl: this.previewUrl + res.fileId,
          fileSizes: res.size
        })
      } else {
        // 提示信息，需引入Message
        this.$message.error('上传失败！')
      }
    },
    beforeUpload(file) {
      return true
    },
    // 文件移除
    beforeRemove(file, fileList) {
      zlxxMenu.removeFile(file.id, res => {
        if (res.state) {
          this.parameter.examFiles.forEach(function(item, index, arr) {
            if (file.id == item.id) {
              arr.splice(index, 1)
            }
          })
          this.$notify({
            type: 'success',
            message: '删除成功',
            duration: 2000
          })
        }
      })
    },
    clearData() {
      if (this.parameter.examMaterialVo.accessControlType == '1') {
        this.UsersList = []
        this.UsersListIds = []
        this.OrgsLists = []
        this.OrgsListIds = []
      }
      if (this.parameter.examMaterialVo.accessControlType == '2') {
        this.UsersList = []
        this.UsersListIds = []
      }
      if (this.parameter.examMaterialVo.accessControlType == '3') {
        this.OrgsLists = []
        this.OrgsListIds = []
      }
    },
    selectOne(val) {
      let arr = JSON.parse(JSON.stringify(this.OrgsLists))
      this.OrgsLists = []
      arr.forEach((p, pi) => {
        val.forEach(v => {
          if (p.accessControlId == v) {
            this.OrgsLists.push(p)
          }
        })
      })
    },
    selectTwo(val) {
      let arr = JSON.parse(JSON.stringify(this.UsersList))
      this.UsersList = []
      arr.forEach((p, pi) => {
        val.forEach(v => {
          if (p.accessControlId == v) {
            this.UsersList.push(p)
          }
        })
      })
    },
    clear() {
      this.OrgsListIds = []
      this.OrgsLists = []
      this.UsersListIds = []
      this.UsersList = []
    },
    selectOrgs() {
      this.$refs.OrgsModal.handleShow(this.OrgsLists)
    },
    selectUsers() {
      this.$refs.UsersModal.handleShow(this.UsersList)
    },
    getOrg(item) {
      console.log(item)
      this.OrgsListIds = []
      this.OrgsLists = item
      this.OrgsLists.forEach(item => {
        this.OrgsListIds.push(item.accessControlId)
      })
    },
    getUser(item) {
      this.UsersListIds = []
      this.UsersList = item
      this.UsersList.forEach(item => {
        this.UsersListIds.push(item.accessControlId)
      })
    },
    // 获取树
    getTreen() {
      zlxxMenu.getMaterTree(
        {
          id: '0'
        },
        res => {
          this.MaterialDataType = res.value
          this.$set(this.MaterialDataType)
        }
      )
    },
    // id查询详情
    getdetail(id) {
      this.UsersList = []
      this.UsersListIds = []
      this.OrgsLists = []
      this.OrgsListIds = []
      zlxxMenu.detailId(id, res => {
        this.parameter = res
        if (this.parameter.examMaterialVo.accessControlType == 2) {
          this.OrgsLists = this.parameter.examMaterialVo.accessControlList
          this.OrgsLists.forEach(s => {
            this.OrgsListIds.push(s.accessControlId)
          })
        } else if (this.parameter.examMaterialVo.accessControlType == 3) {
          this.UsersList = this.parameter.examMaterialVo.accessControlList
          this.UsersList.forEach(s => {
            this.UsersListIds.push(s.accessControlId)
          })
        }
        this.parameter.examFiles.forEach(item => {
          this.fileList.push({
            name: item.fileName,
            url: item.fileUrl
            // id: item.id
          })
        })
      })
    },
    handleChange(val) {
      let ArrIds = []
      ArrIds = val
      if (ArrIds.length == 0) {
        this.parameter.typeId = ArrIds[0]
      } else {
        this.parameter.typeId = ArrIds[val.length - 1]
      }
    },
    add(val) {
      this.title = '新增'
      this.visible = true
      this.getTreen()
    },
    edit(val) {
      this.title = '修改'
      this.visible = true
      this.getTreen()
      this.getdetail(val.id)
    },
    // 关闭新增人员窗口
    handleClose() {
      this.visible = false
      this.title = '新增'
      this.parameter = {
        examFiles: [],
        examMaterialVo: {
          accessControlList: [],
          accessControlType: '',
          authType: '',
          typeId: ''
        },
        keyword: '',
        memo: '',
        title: '',
        typeId: ''
      }
      this.fileList = []
    },
    // 保存产品类型
    handleSave() {
      this.parameter.examMaterialVo.accessControlList = []
      if (this.parameter.examFiles.length > 0) {
        this.parameter.examFiles.forEach(e => {
          delete e.createTime
          delete e.fileExt
          delete e.fileType
          delete e.isDele
          delete e.materialId
          delete e.pkVal
          delete e.id
        })
      }

      if (this.OrgsLists.length != 0) {
        // this.OrgsLists.forEach(item => {
        // 	let obj = {}
        // 	obj["accessControlId"] = item.id
        // 	obj["accessControlName"] = item.name
        // 	this.parameter.examMaterialVo.accessControlList.push(obj)
        // })
        this.parameter.examMaterialVo.accessControlList = this.OrgsLists
      }
      if (this.UsersList.length != 0) {
        // this.UsersList.forEach(item => {
        // 	let obj = {}
        // 	obj["accessControlId"] = item.id
        // 	obj["accessControlName"] = item.fullname
        // 	this.parameter.examMaterialVo.accessControlList.push(obj)
        // })
        this.parameter.examMaterialVo.accessControlList = this.UsersList
      }

      this.$refs.formInfo.validate(valid => {
        if (valid) {
          let method
          if (this.title === '新增') {
            method = zlxxMenu.addMaterial
          }
          if (this.title === '修改') {
            method = zlxxMenu.editMaterial
          }
          method(this.parameter, response => {
            if (response.state) {
              this.$notify({
                type: 'success',
                message: this.title + '成功',
                duration: 2000
              })
              this.handleClose()
              this.$emit('loadData')
            } else {
              this.$message.warning(response.message)
            }
          })
        }
      })
    }
  }
}
</script>

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