<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发文字号" prop="issuedNum">
        <el-input v-model="queryParams.issuedNum" placeholder="请输入发文字号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="标题" prop="issuedName">
        <el-input v-model="queryParams.issuedName" placeholder="请输入发文标题" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!--      <el-form-item label="密级" prop="issuedLevel">-->
      <!--        <el-select v-model="queryParams.issuedLevel" @keyup.enter.native="handleQuery" style="width: 100%"-->
      <!--                   placeholder="请选择密级">-->
      <!--          <el-option v-for="dict in dict.type.secret_level" :key="dict.value" :label="dict.label"-->
      <!--                     :value="dict.value"></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <el-form-item label="紧急程度" label-width="100px" prop="urgency">
        <el-select v-model="queryParams.urgency" style="width: 100%" placeholder="请选择紧急程度">
          <el-option v-for="dict in dict.type.urgency" :key="dict.value" :label="dict.label"
                     :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" style="width: 100%" placeholder="请选择状态">
          <el-option v-for="dict in dict.type.official_state" :key="dict.value" :label="dict.label"
                     :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:official:add']">新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="officialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="发文字号" align="center" min-width="100" prop="issuedNum"/>
      <el-table-column label="标题" align="center" prop="issuedName" width="120" :show-overflow-tooltip="true"/>
      <!--      <el-table-column label="密级" align="center" prop="issuedLevel">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.secret_level" :value="scope.row.issuedLevel"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="紧急程度" align="center" prop="urgency">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.urgency" :value="scope.row.urgency"/>
        </template>
      </el-table-column>

      <el-table-column label="收文时间" align="center" prop="receiveDate" min-width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="办理期限" align="center" prop="deadline" min-width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deadline, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="文件" align="center" prop="fileList" width="180" :show-overflow-tooltip="true">-->
      <!--        <template slot-scope="scope">-->
      <!--          <div v-for="(item, index) in scope.row.fileList">-->
      <!--            <h4>{{ scope.row.fileList[index].fjmc }}</h4>-->
      <!--          </div>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="简介" align="center" min-width="150" prop="remarks"/>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.official_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="170px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.state == 0" size="mini" type="text" icon="el-icon-edit"
                     @click="handleUpdate(scope.row)" v-hasPermi="['system:official:edit']">修改
          </el-button>
          <el-button v-if="scope.row.state == 0" size="mini" icon="el-icon-document-checked" type="text"
                     @click="submitTable(scope.row)">发文
          </el-button>
          <el-button size="mini" icon="el-icon-view" type="text" @click="view(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:official:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="发文字号" prop="issuedNum">
              <el-input v-model="form.issuedNum" placeholder="请输入发文字号"/>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="密级" prop="issuedLevel">-->
          <!--              <el-select v-model="form.issuedLevel" style="width: 100%" placeholder="请选择密级">-->
          <!--                <el-option v-for="dict in dict.type.secret_level" :key="dict.value" :label="dict.label"-->
          <!--                           :value="dict.value"></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>

        <el-form-item label="发文标题" prop="issuedName">
          <el-input v-model="form.issuedName" placeholder="请输入发文标题"/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收文时间" prop="receiveDate">
              <el-date-picker clearable style="width: 100%" v-model="form.receiveDate" type="date"
                              value-format="yyyy-MM-dd" placeholder="请选择收文时间"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="办理期限" prop="deadline">
              <el-date-picker clearable style="width: 100%" v-model="form.deadline" type="date"
                              value-format="yyyy-MM-dd" placeholder="请选择办理期限"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="紧急程度" prop="urgency">
              <el-select v-model="form.urgency" style="width: 100%" placeholder="请选择紧急程度">
                <el-option v-for="dict in dict.type.urgency" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批阅人" prop="userName">
              <el-input v-model="form.userName" @click.native="selectReceiveUser" placeholder="请选择批阅人"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="简介" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="上传文件" prop="fileList">
          <el-upload class="upload-demo" action="#" :before-remove="beforeRemove" :on-remove="handleRemove"
                     multiple :limit="5" :on-exceed="handleExceed"
                     :file-list="fileList"
                     :http-request="uploadFile">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="temporary">暂存</el-button>
        <el-button type="primary" @click="submitForm">发文</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择批阅人-->
    <el-dialog title="选择批阅人" :visible.sync="openSelect" width="800px" append-to-body style="padding: 0 0 0 0">
      <div>
        <el-form :model="selectQuery" ref="queryForm" size="small" :inline="true"
                 label-width="68px">
          <el-form-item label="教师名称" prop="teacherName">
            <el-input v-model="selectQuery.teacherName" placeholder="请输入教师名称" clearable/>
          </el-form-item>
          <el-form-item label="教师电话" prop="teacherTel">
            <el-input v-model="selectQuery.teacherTel" placeholder="请选择老师电话" clearable/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="searchReceiveUserName">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetReceiveUserName">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table style="width:720px;margin:0 25px 0 25px;height: 350px;" ref="multipleTable" max-height="350"
                  v-loading="selectLoading" :data="schoolLeaderList" size="small" highlight-current-row
                  @row-click="handleCurrentChange" @selection-change="select" @select-all="selectAll">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column prop="picUrl" width="80" label="头像" align="center">
            <template slot-scope="scope">
              <ListImage :image-url="pev + scope.row.avatar"></ListImage>
            </template>
          </el-table-column>
          <el-table-column label="老师名称" width="100" align="center" prop="teacherName"/>
          <el-table-column prop="sex" width="60" label="性别" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
            </template>
          </el-table-column>
          <el-table-column prop="teacherTel" width="100" label="老师电话" align="center">
          </el-table-column>
          <el-table-column prop="deptName" label="部门名称" align="center">
          </el-table-column>
        </el-table>

        <pagination v-show="selectTotal > 0" :total="selectTotal" :page.sync="selectQuery.pageNum"
                    :limit.sync="selectQuery.pageSize" @pagination="selectReceiveUser"/>
        <div style="text-align: center; margin: 35px 0 0 0">
          <el-button type="primary" @click="selectConfirm" size="small" style="margin: 0 10px 0 0">确 定
          </el-button>
          <el-button @click="close" size="small" style="margin: 0 30px 0 10px">取 消
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOfficial,
  getOfficial,
  delOfficial,
  addOfficial,
  publicDocument,
  getApprover,
  commonUpload,
  updateOfficial
} from '@/api/smartSchool/schoolManage/documentFlow'

export default {
  name: 'Official',
  dicts: ['secret_level', 'urgency', 'official_state', 'sys_user_sex'],
  data() {
    return {
      pev: process.env.VUE_APP_BASE_API,
      //批阅人列表
      schoolLeaderList: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      officialList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 选择批阅人弹出层
      openSelect: false,
      selectLoading: false,
      //为了upload 上面解决后端字段名问题
      fileList: [],
      selectTotal: 0,
      // 批阅人查询参数
      selectQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        issuedNum: undefined,
        issuedName: undefined,
        // issuedLevel: undefined,
        receiveDate: undefined,
        deadline: undefined,
        urgency: undefined,
        remarks: undefined,
        state: undefined
      },
      // 表单参数
      form: {},
      // 上传文件名
      fileName: [],
      // 表单校验
      rules: {
        issuedNum: [{required: true, message: '发文字号不能为空', trigger: 'blur'}],
        issuedName: [{required: true, message: '发文标题不能为空', trigger: 'blur'}],
        userName: [{required: true, message: '批阅人不能为空', trigger: 'change'}],
        receiveDate: [{required: true, message: '收文时间不能为空', trigger: 'change'}],
        deadline: [{required: true, message: '办理期限不能为空', trigger: 'change'}],
        urgency: [{required: true, message: '紧急程度不能为空', trigger: 'change'}],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 列表 */
    getList() {
      this.loading = true
      listOfficial(this.queryParams).then(response => {
        // console.log(response.rows)
        this.officialList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        issuedNum: null,
        issuedName: null,
        // issuedLevel: null,
        receiveDate: null,
        deadline: null,
        urgency: null,
        userName: null,
        remarks: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        state: null,
        delFlag: null,
        fileList: []
      }
      this.fileList = []
      // this.index = 0
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    formatArray(array) {
      let newArray = array.map(item => {
        return {label: item.teacherName, value: item.id}
      })
      return newArray
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增'
    },
    // 搜索批阅人
    searchReceiveUserName() {
      this.selectLoading = true
      getApprover(this.selectQuery).then(res => {
        this.schoolLeaderList = res.rows
        this.selectTotal = res.total
        this.selectLoading = false
      })
    },
    resetReceiveUserName() {
      this.selectQuery = {
        pageNum: 1,
        pageSize: 10,
      }
      this.searchReceiveUserName()
    },
    // 选择批阅人
    selectReceiveUser() {
      this.openSelect = true
      this.searchReceiveUserName()
    },
    // 多选
    select(selection) {
      if (selection.length > 1) {
        this.$refs.multipleTable.toggleRowSelection(selection[0], false);
        selection.shift();  //删除上一个选项
      }
      if (selection.length = 1) {
        this.form.userName = selection[0].teacherName;
        this.form.receiveUser = selection[0].id;
      }
    },
    selectAll(selection) {
      this.$refs.multipleTable.clearSelection()
    },
    //单选
    handleCurrentChange(row) {
      if (row.id) {
        this.form.receiveUser = row.id;
        this.$set(this.form, "userName", row.teacherName)
      }
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    close() {
      this.openSelect = false
    },
    // 确认批阅人
    selectConfirm() {
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      })
      this.openSelect = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOfficial(id).then(response => {
        this.form = response.offical
        if (response.offical.fileList != null) {
          console.log(response.offical.fileList, 429)
          this.form.fileList = response.offical.fileList
          this.fileList = []
          for (let i = 0; i < this.form.fileList.length; i++) {
            let arr = {
              name: this.form.fileList[i].fjmc,
              url: this.form.fileList[i].fjdz,
              fjlx: this.form.fileList[i].fjlx
            }
            this.fileList.push(arr)
          }
        }
        this.open = true
        this.title = '编辑'
      })
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => {
        if (item.name != file.name) {
          return true
        } else {
          return false
        }
      })
      this.form.fileList = []
      this.fileList.map((item) => {
        let arr = {fjdz: item.url, fjmc: item.name, fjlx: item.fjlx,}
        this.form.fileList.push(arr)
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 上传文件
    uploadFile(file) {
      const fileData = file.file
      const formData = new FormData()
      formData.append('file', fileData)
      this.uploadLoading = true
      commonUpload(formData).then(response => {
        this.uploadLoading = false
        this.$modal.msgSuccess('上传成功')
        console.log(response, 476)
        let tem = {fjdz: response.data.fjdz, fjmc: response.data.fjmc, fjlx: response.data.fjlx,}
        this.fileList.push({name: response.data.fjmc, url: response.data.fjdz, fjlx: response.data.fjlx})
        this.form.fileList.push(tem)
      }).catch(error => {
        this.uploadLoading = false
      })
    },
    //暂存
    temporary() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          addOfficial(this.form).then(response => {
            this.$modal.msgSuccess('暂存成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 表单发文按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // this.form.fileList = this.fileList
          updateOfficial(this.form).then(response => {
            this.$modal.msgSuccess('发文成功')
            this.open = false
            this.getList()
          })
        }
      })
    },

    /** 表格发文按钮 */
    submitTable(row) {
      this.loading = true
      publicDocument(row.id).then(response => {
        this.$modal.msgSuccess('发文成功')
        this.loading = false
        this.getList()
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除？')
        .then(function () {
          return delOfficial(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/official/export',
        {
          ...this.queryParams
        },
        `official_${Date.now()}.xlsx`
      )
    },
    view(row) {
      this.$router.push({
        path: '/schoolManage/documentFlowView',
        query: {
          id: row.id,
          back: 'schoolManage'
        }
      })
    }
  }
}
</script>
