<template>
  <div class="main-content m20">
    <!--头部-查询-->
    <div class="content-header">
      <searchHeader title="查询" />
      <div class="body search-body">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-row class="mb10">
              <label class="label-name" style="width: 150px">惩戒措施(模糊)：</label>
              <div class="search-input-box" style="width: calc(100% - 150px)">
                <el-input v-model="searchForm.searchMeasure" size="mini" clearable type="text" class="search-input" placeholder="请输入惩戒措施(模糊)" @keyup.enter.native="search" />
              </div>
            </el-row>
          </el-col>
          <el-col :span="6">
            <el-row class="mb10">
              <label class="label-name" style="width: 80px">认定部门：</label>
              <el-select v-model="searchForm.searchDepart" size="mini" filterable clearable placeholder="请选择" style="width: calc(100% - 100px);">
                <el-option
                  v-for="item in departmentList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-row>
          </el-col>
          <!-- <el-col :span="6">
            <label class="label-name" style="width: 120px">文书号（模糊）：</label>
            <div class="search-input-box" style="width: calc(100% - 130px)">
              <el-input v-model="searchForm.searchWritsNo" size="mini" clearable type="text" class="search-input" placeholder="请输入文书号（模糊）" @keyup.enter.native="search" />
            </div>
          </el-col> -->
          <el-col :span="4" :offset="4">
            <div class="btn-box">
              <el-button type="primary" size="mini" @click="search">查询</el-button>
              <el-button size="mini" @click="searchForm.searchMeasure='';searchForm.searchDepart = '';">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--body-查询结果-->
    <div class="content-body">
      <div class="body">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 95%;margin:0 auto"
          :fit="true"
          border
          :row-class-name="tableRowClassName"
          :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
          @selection-change="handleSelectionChange"
        >
          <el-table-column class="no" type="selection" min-width="25" align="center" />
          <el-table-column prop="index" label="序号" min-width="40" align="center" />
          <el-table-column prop="measure" :show-overflow-tooltip="true" label="惩戒措施" min-width="150" align="left" />
          <el-table-column prop="punishObject" :show-overflow-tooltip="true" label="惩戒对象" min-width="160" align="left" />
          <el-table-column prop="illegalAct" :show-overflow-tooltip="true" label="失信行为" min-width="200" align="left" />
          <el-table-column prop="memorandumBase" :show-overflow-tooltip="true" label="备忘录依据" min-width="140" align="left" />
          <el-table-column prop="department" :show-overflow-tooltip="true" label="对象认定部门" min-width="90" align="left" />
          <el-table-column label="操作" min-width="100" align="left">
            <!-- <template slot="header" slot-scope="scope">
              <label style="margin-right:10px">操作</label>
              <el-button
                size="mini"
                type="primary"
                @click="insertDialog = true"
              >新增</el-button>
            </template> -->
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="edit(scope.row)">编辑</el-button>
              <!-- <el-button type="danger" size="mini" @click="deleteById(scope.row)">删除</el-button> -->

              <!-- <i style="margin-right: 5px" class="el-icon-view icon" />
              <i style="margin-right: 5px" class="el-icon-edit icon" />
              <i class="el-icon-lock icon" /> -->
            </template>
          </el-table-column>
        </el-table>
        <div class="page-box">
          <el-row>
            <el-col :span="6">
              <el-button
                size="mini"
                type="primary"
                @click="insertDialog = true"
              >新增</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="deleteSelected()"
              >删除</el-button>
              <!-- <el-button @click="selectAll">全选</el-button>
              <el-button @click="$util.toggleSelect($refs.multipleTable)">反选</el-button>
              <el-button type="primary" @click="startTask">办理</el-button> -->
            </el-col>
            <el-col :span="18">
              <el-pagination
                :disabled="loading"
                :page-size="pageParam.pageSize"
                :total="pageParam.total"
                :page-sizes="[10, 20, 30, 40,50,100,200]"
                layout="slot,total, sizes, prev, pager, next, jumper"
                @size-change="pageSizeChange"
                @current-change="pageIndexChange"
              >
                <!-- <batchFunction :options="options" style="float:left" /> -->
                <span>
                  第 {{ pageParam.curPage }} 页 /
                  共 {{ (pageParam.total !== 0 ? parseInt((pageParam.total + pageParam.pageSize - 1)/pageParam.pageSize) : 1) }} 页
                </span>
              </el-pagination>
            </el-col>
          </el-row>
        </div>
        <!--分页多选组件-->
        <!-- <pageSelector :selection="selection" :columns="selectionColumn" @removeCallback="removeCallback" /> -->
      </div>
    </div>
    <el-dialog
      title="新增措施"
      :visible.sync="insertDialog"
      width="40%"
    >
      <el-form ref="measureForm" :model="measureForm" :rules="rules" label-width="130px">
        <el-form-item label="惩戒措施" prop="measure">
          <el-input v-model="measureForm.measure" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" />
        </el-form-item>
        <el-form-item label="惩戒对象" prop="punishObject">
          <el-input v-model="measureForm.punishObject" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" />
        </el-form-item>
        <el-form-item label="失信行为" prop="illegalAct">
          <el-input v-model="measureForm.illegalAct" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" />
        </el-form-item>
        <el-form-item label="备忘录依据" prop="memorandumBase">
          <el-input v-model="measureForm.memorandumBase" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" />
        </el-form-item>
        <el-form-item label="对象认定部门" prop="department">
          <!-- <el-input v-model="measureForm.department" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" /> -->
          <el-select v-model="measureForm.department" size="mini" filterable clearable style="width: 100%;">
            <el-option
              v-for="item in departmentList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="insertDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveMeasure()">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="编辑措施"
      :visible.sync="editDialog"
      width="40%"
    >
      <el-form ref="measureEditForm" :model="measureEditForm" :rules="rules" label-width="130px">
        <el-form-item label="惩戒措施" prop="measure">
          <el-input v-model="measureEditForm.measure" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" />
        </el-form-item>
        <el-form-item label="惩戒对象" prop="punishObject">
          <el-input v-model="measureEditForm.punishObject" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" />
        </el-form-item>
        <el-form-item label="失信行为" prop="illegalAct">
          <el-input v-model="measureEditForm.illegalAct" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" />
        </el-form-item>
        <el-form-item label="备忘录依据" prop="memorandumBase">
          <el-input v-model="measureEditForm.memorandumBase" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" />
        </el-form-item>
        <el-form-item label="对象认定部门" prop="department">
          <!-- <el-input v-model="measureEditForm.department" type="textarea" :autosize="{ minRows: 1, maxRows: 6 }" /> -->
          <el-select v-model="measureEditForm.department" size="mini" filterable clearable style="width: 100%;">
            <el-option
              v-for="item in departmentList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveEditMeasure()">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import searchHeader from '@/components/searchHeader'
import pageSelector from '@/components/PageSelector'
import { getDepartmentList, measureListPage, deleteMeasure, savePunishMeasure } from '@/api/punishment'

export default {
  components: {
    pageSelector: pageSelector,
    searchHeader
  },
  data() {
    return {
      measureEditForm: {},
      measureForm: {
        measure: '',
        punishObject: '',
        illegalAct: '',
        memorandumBase: '',
        department: '',
        departmentCode: ''
      },
      rules: {
        measure: [
          { required: true, message: '请输入惩戒措施', trigger: 'blur' }
        ],
        punishObject: [
          { required: true, message: '请输入惩戒对象', trigger: 'blur' }
        ],
        illegalAct: [
          { required: true, message: '请输入失信行为', trigger: 'blur' }
        ],
        memorandumBase: [
          { required: true, message: '请输入备忘录依据', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请选择对象认定部门', trigger: 'change' }
        ]
      },
      insertDialog: false,
      editDialog: false,
      departmentList: [],
      punishFromList: [],
      lockTypeOptions: [],
      selection: [],
      selectionColumn: [{ label: '序号', type: 'index' }, { label: '统一社会信用代码/注册号', prop: 'uscc' }, { label: '主体名称', prop: 'entname' }],
      searchForm: {
        searchDepart: '',
        searchMeasure: ''
      },
      loading: false,
      tableData: [],
      pageParam: {
        customParamMap: {},
        curPage: 1,
        total: 0,
        pageSize: 10
      }
    }
  },
  mounted() {
    // 加载认定部门
    this.departmentList = getDepartmentList()
    this.loadPage()
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    // 删除已选
    deleteSelected() {
      let ids = ''
      this.selection.forEach(each => {
        ids += (each.measureId + ';')
      })
      this.$confirm('是否确定删除？', '提示').then(() => {
        deleteMeasure(ids.substring(0, ids.length - 1)).then(res => {
          if (res.data === true) {
            this.$message.success('删除成功')
            this.loadPage()
          } else {
            this.$message.error('删除失败')
          }
        })
      })
    },
    saveMeasure() {
      this.$refs.measureForm.validate((valid, obj) => {
        if (!valid) {
          console.log(obj)
          this.$message.error(obj[Object.keys(obj)[0]][0].message)
        } else {
          this.departmentList.forEach(each => {
            console.log(each.label + '========================' + this.measureForm.department)
            if (each.label === this.measureForm.department) {
              console.log('========================')
              this.measureForm.departmentCode = each.value
            }
          })
          this.$confirm('是否确定保存？', '提示').then(() => {
            savePunishMeasure(this.measureForm).then(res => {
              if (res.data === true) {
                this.insertDialog = false
                this.$message.success('保存成功！')
                this.loadPage()
              }
            })
          })
        }
      })
    },
    saveEditMeasure() {
      this.$refs.measureEditForm.validate((valid, obj) => {
        if (!valid) {
          console.log(obj)
          this.$message.error(obj[Object.keys(obj)[0]][0].message)
        } else {
          this.departmentList.forEach(each => {
            if (each.label === this.measureEditForm.department) {
              this.measureEditForm.departmentCode = each.value
            }
          })
          this.$confirm('是否确定保存？', '提示').then(() => {
            savePunishMeasure(this.measureEditForm).then(res => {
              if (res.data === true) {
                this.editDialog = false
                this.$message.success('保存成功！')
                this.loadPage()
              }
            })
          })
        }
      })
    },
    createTimeFormat(row) {
      if (this.$util.isEmpty(row.createtime)) {
        return ''
      } else {
        return this.$util.formatDate.format(new Date(Date.parse(row.createtime)), 'yyyy-MM-dd hh:mm:ss')
      }
    },
    edit(row) {
      this.measureEditForm = JSON.parse(JSON.stringify(row))
      this.editDialog = true
    },
    deleteById(row) {
      this.$confirm('是否确定删除？', '提示').then(() => {
        deleteMeasure(row.measureId).then(res => {
          if (res.data === true) {
            this.$message.success('删除成功')
          }
        })
      })
    },
    // 搜索
    search() {
      this.pageParam.customParamMap = this.searchForm
      this.pageParam.curPage = 1
      this.loadPage()
    },
    // 分页多选插件回调
    removeCallback(index, row) {
      this.$refs.multipleTable.toggleRowSelection(row, false)
    },
    // 全选按钮事件
    selectAll() {
      const table = this.$refs.multipleTable
      for (const i in table.data) {
        const each = table.data[i]
        table.toggleRowSelection(each, true)
      }
    },
    // 选项变更事件
    handleSelectionChange(selectData) {
      const cancel = []
      if (selectData.length !== this.tableData.length) {
        // 找出没有选中的内容
        this.tableData.forEach(each => {
          for (const i in selectData) {
            const atom = selectData[i]
            if (atom.measureId === each.measureId) {
              return
            }
          }
          cancel.push(each)
        })
      }
      // 取消选中的内容
      for (const i in cancel) {
        const each = cancel[i]
        let index
        for (const j in this.selection) {
          const select = this.selection[j]
          if (select.measureId === each.measureId) {
            index = parseInt(j)
            break
          }
        }
        if (index !== undefined) {
          this.selection.splice(index, 1)
        }
      }
      // 增加选中内容
      for (const i in selectData) {
        const each = selectData[i]
        let exist = false
        for (const j in this.selection) {
          const select = this.selection[j]
          if (select.measureId === each.measureId) {
            exist = true
            break
          }
        }
        if (!exist) {
          this.selection.push(each)
        }
      }
    },
    // 当前分页改变
    pageIndexChange(curPage) {
      this.pageParam.curPage = curPage
      this.loadPage()
    },
    // 分页大小改变
    pageSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize
      this.loadPage()
    },
    // 加载分页
    loadPage() {
      if (this.loading) return
      this.loading = true
      measureListPage(this.pageParam).then(res => {
        this.loading = false
        const list = []
        let i = 1
        const pageStart = (this.pageParam.curPage - 1) * this.pageParam.pageSize
        res.data.records.forEach(each => {
          each.index = pageStart + i++
          list.push(each)
        })
        this.tableData = list
        this.pageParam.total = res.data.total
        const selection = JSON.parse(JSON.stringify(this.selection))
        this.$nextTick(() => {
          for (const i in list) {
            const each = list[i]
            for (const j in selection) {
              if (each.measureId === selection[j].measureId) {
                this.$refs.multipleTable.toggleRowSelection(each, true)
              }
            }
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-content{
  background: #fff;
  .content-header{
    background: white;
    .label-name {
      text-align: right;
      display: inline-block;
      width: 120px;
      font-size: $table-content-font-size;
    }
    .search-input-box{
      display: inline-block;
      width: calc(100% - 150px);
    }
    .custom{
      width: calc(100% - 100px);
    }
    .search-input{
      cursor: pointer;
    }
    .body{
      padding:10PX;
      border-top:none;
      margin-bottom: 40PX;
    }
  }
  .content-body{
    background:white;
  }
  .header{
    .title{
      font-weight: 600;
      font-size: 1.2rem;
    }
  }
    .icon{
    font-size: 50px;
    color: rgb(24, 144, 255);
  }
  .page-box{
    margin:10PX;
    .el-pagination{
      text-align: right;
    }
  }
  .mb10{
    margin-bottom: 10px;
  }
}
</style>
