<template>
  <div class="main-content m20">
    <!--头部-查询-->
    <div class="content-header">
      <div class="body search-body">
        <el-row style="margin-bottom:10px">
          <el-col :span="12">
            <label class="label-name" style="width: 220px">违法行为代码：</label>
            <div class="search-input-box" style="width: calc(100% - 220px)">
              <el-input v-model="searchForm.code" clearable size="mini" type="text" class="search-input" placeholder="请输入违法行为代码" @keyup.enter.native="search" />
            </div>
          </el-col>
          <el-col :span="12">
            <label class="label-name">违法行为描述：</label>
            <div class="search-input-box">
              <el-input v-model="searchForm.label" clearable size="mini" type="text" class="search-input" placeholder="请输入违法行为描述" @keyup.enter.native="search" />
            </div>
          </el-col>
        </el-row>
        <el-row v-if="showMore" style="margin-bottom:10px" />
        <el-row v-if="showMore" style="margin-bottom:10px" />
        <el-row>
          <el-col :span="6" :offset="1">
            <div class="btn-box" style="font-size: 14px">
              <span v-if="!showMore" style="margin-right:20px;color:#409EFF;cursor:pointer" @click="showMoreCriteria">
                展开<i class="el-icon-d-arrow-right" />
              </span>
              <span v-if="showMore" style="margin-right:20px;color:#409EFF;cursor:pointer" @click="showMoreCriteria">
                <i class="el-icon-d-arrow-left" />隐藏
              </span>
              <el-button type="primary" size="mini" @click="search">查询</el-button>
              <el-button size="mini" @click="resetSearchForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--body-查询结果-->
    <div class="content-body">
      <div class="body">
        <el-row style="width: 95%;padding: 0;margin:0 auto">
          <label style="font-size:16px">当前所处: {{ pos }}</label>
        </el-row>
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
          :row-class-name="tableRowClassName"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 95%;padding: 0;margin:0 auto"
          :fit="true"
          @selection-change="handleSelectionChange"
        >
          <!-- <el-table-column class="no" type="selection" min-width="30" align="center" /> -->
          <el-table-column prop="index" label="序号" min-width="40" align="center" />
          <el-table-column prop="code" label="违法行为代码" min-width="100" align="left" />
          <el-table-column prop="label" :show-overflow-tooltip="true" label="违法行为" min-width="400" align="left">
            <template slot-scope="scope">
              <el-link type="primary" style="font-size:16px" :show-overflow-tooltip="true" @click="getChildList(scope.row)">{{ scope.row.label }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="level" :show-overflow-tooltip="true" label="类别" min-width="120" align="left" :formatter="levelFormatter" />
          <el-table-column prop="sort" label="排序" min-width="80" align="left" />
          <el-table-column prop="isValid" :show-overflow-tooltip="true" label="状态" min-width="80" align="left">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isValid === '1'" type="success">正常</el-tag>
              <el-tag v-if="scope.row.isValid === '0'" type="info">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="90" align="left" :formatter="(row, column, cellValue, index)=>{return parseTime(cellValue, '{yyyy}-{mm}-{dd}')}" />
          <el-table-column label="操作" min-width="60" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="showUpdateForm(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-box">
          <el-row class="bl0" style="width: 95%;padding: 0;margin:0 auto">
            <el-col :span="8">
              <el-button v-if="listType === 'L'" type="primary" size="mini" @click="showInsertForm">新增</el-button>
              <el-button v-if="listType === 'M' || listType === 'S'" type="primary" size="mini" @click="showInsertFormM">新增</el-button>
              <el-button v-if="listType === 'M' || listType === 'S'" type="primary" size="mini" @click="search">返回大类列表</el-button>
              <el-button v-if="listType === 'S'" type="primary" size="mini" @click="backToM">返回中类列表</el-button>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
              <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="dialogVisible"
      width="30%"
    >
      <el-form ref="insertForm" :model="insertForm" :rules="rules" label-width="80px">
        <el-form-item label="描述" prop="label">
          <el-input v-model="insertForm.label" type="textarea" :autosize="{ minRows: 1 }" />
        </el-form-item>
        <!-- <el-form-item label="所属模块" prop="module">
          <el-select v-model="insertForm.module">
            <el-option
              v-for="module in modules"
              :key="module"
              :value="module"
              :label="module"
            >
              {{ module }}
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="排序" prop="sort">
          <el-input v-model="insertForm.sort" />
        </el-form-item>
        <el-form-item label="状态：" prop="isValid">
          <template>
            <el-radio v-model="insertForm.isValid" label="1">正常</el-radio>
            <el-radio v-model="insertForm.isValid" label="0">停用</el-radio>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" :loading="addLoading" @click="addIllegalAct('insertForm')">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="listType === 'M' ? '新增违法行为中类':'新增违法行为小类'"
      :visible.sync="dialogVisibleM"
      width="30%"
    >
      <el-form ref="insertFormM" :model="insertFormM" :rules="rules" label-width="80px">
        <el-form-item label="描述" prop="label">
          <el-input v-model="insertFormM.label" type="textarea" :autosize="{ minRows: 1 }" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="insertFormM.sort" />
        </el-form-item>
        <el-form-item label="状态：" prop="isValid">
          <template>
            <el-radio v-model="insertFormM.isValid" label="1">正常</el-radio>
            <el-radio v-model="insertFormM.isValid" label="0">停用</el-radio>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisibleM = false">取 消</el-button>
        <el-button size="mini" type="primary" :loading="addLoading" @click="addIllegalActM('insertFormM')">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改"
      :visible.sync="editDialog"
      width="30%"
    >
      <el-form ref="updateForm" :model="updateForm" :rules="rules" label-width="80px">
        <el-form-item label="违法行为" prop="label">
          <el-input v-model="updateForm.label" type="textarea" :autosize="{ minRows: 1 }" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="updateForm.sort" />
        </el-form-item>
        <el-form-item label="状态：" prop="isValid">
          <template>
            <el-radio v-model="updateForm.isValid" label="1">正常</el-radio>
            <el-radio v-model="updateForm.isValid" label="0">停用</el-radio>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" :loading="addLoading" @click="updateIllegalAct('updateForm')">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import searchHeader from '@/components/searchHeader'
import pageSelector from '@/components/PageSelector'
import { saveAbnormalAccept, validateBiz } from '@/api/abnormal'
import { saveIllegalAct, codeListPageByType, updateDictCode, codeChildrenList, saveIllegalActM } from '@/api/dict'
import { getConstant } from '@/api/system'
import { parseTime } from '@/utils'
export default {
  components: {
    pageSelector: pageSelector,
    searchHeader
  },
  data() {
    return {
      pos: '违法行为',
      updateForm: {
        label: '',
        sort: '',
        isValid: ''
      },
      insertForm: {
        isValid: '1',
        label: '',
        sort: ''
      },
      insertFormM: {
        isValid: '1',
        label: '',
        sort: '',
        parentid: '',
        parentCode: '',
        parentLevel: ''
      },
      fileList: [],
      bustypeOptions: [],
      showMore: false,
      nextLoading: false,
      templateDialog1: false,
      templateDialog: false,
      uploadPath: `${process.env.VUE_APP_BASE_API}/bizSpeList/upload`,
      selection: [],
      rules: {
        isValid: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ],
        label: [
          { required: true, message: '请输入违法行为', trigger: 'blur' }
        ]
      },
      searchForm: {
        code: '',
        label: '',
        type: 'illegalAct'
      },
      loading: false,
      showFixed: false,
      tableData: [],
      pageParam: {
        customParamMap: {
          type: 'illegalAct',
          level: '',
          id: ''
        },
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      childPageParam: {
        customParamMap: {
          parentid: ''

        },
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      showReprtYear: false,
      showRegEntryUserName: false,
      reasonOptions: [],
      dialogVisible: false,
      dialogVisibleM: false,
      addLoading: false,
      editDialog: false,
      listType: 'L',
      mParentId: ''
    }
  },
  computed: {
    fixedHeader() {
      return this.$store.state.settings.fixedHeader
    }
  },
  watch: {
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
  },
  methods: {
    // 获取子列表
    getChildList(row) {
      if (row.level === 0) {
        this.listType = 'M'
        this.mParentId = row.id
      } else if (row.level === 1) {
        this.listType = 'S'
      } else {
        return
      }
      this.insertFormM.parentid = row.id
      this.insertFormM.parentCode = row.code
      this.insertFormM.parentLevel = row.level
      this.pos = row.label
      this.clearCustomParamMap()
      this.pageParam.customParamMap.id = row.id
      this.getCodeChildrenList()
    },
    backToM() {
      this.getChildListwithId(this.mParentId)
      this.listType = 'M'
    },
    getChildListwithId(id) {
      this.clearCustomParamMap()
      this.pageParam.customParamMap.id = id
      this.getCodeChildrenList()
    },
    getCodeChildrenList() {
      codeChildrenList(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.pripid === selection[j].pripid) {
                this.$refs.multipleTable.toggleRowSelection(each, true)
              }
            }
          }
        })
      })
    },
    updateIllegalAct() {
      updateDictCode({
        id: this.updateForm.id,
        sort: this.updateForm.sort,
        isValid: this.updateForm.isValid,
        label: this.updateForm.label
      }).then(res => {
        if (res.data === true) {
          this.$message({
            message: '修改成功',
            type: 'success',
            center: true
          })
          this.editDialog = false
          if (this.listType === 'L') {
            return this.getLargeList()
          } else {
            return this.getChildListwithId(this.insertFormM.parentid)
          }
        }
      })
    },
    showUpdateForm(row) {
      this.editDialog = true
      Object.assign(this.updateForm, row)
      console.log(this.updateForm)
    },
    levelFormatter(row) {
      const list = [{
        value: 0,
        label: '违法行为大类'
      }, {
        value: 1,
        label: '违法行为中类'
      }, {
        value: 2,
        label: '违法行为小类'
      }]
      return this.$util.enumFormatter(list, row.level)
    },
    showInsertForm() {
      this.dialogVisible = true
    },
    showInsertFormM() {
      this.dialogVisibleM = true
    },
    // 新增违法行为大类
    addIllegalAct(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addLoading = true
          saveIllegalAct({
            ...this.insertForm
          }).then(res => {
            if (res.data === true) {
              this.$message({
                message: '新增成功',
                type: 'success',
                center: true
              })
              this.dialogVisible = false
              return this.getLargeList()
            }
          }).finally(() => {
            this.addLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 新增违法行为中、小类
    addIllegalActM(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addLoading = true
          saveIllegalActM({
            ...this.insertFormM
          }).then(res => {
            if (res.data === true) {
              this.$message({
                message: '新增成功',
                type: 'success',
                center: true
              })
              this.dialogVisibleM = false
              return this.getChildListwithId(this.insertFormM.parentid)
            }
          }).finally(() => {
            this.addLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    parseTime(...args) {
      return parseTime(...args)
    },
    showMoreCriteria() {
      this.showMore = !this.showMore
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    // 重置搜索表单
    resetSearchForm() {
      this.searchForm = {
        code: '',
        label: ''
      }
    },
    reasonFormatter(row) {
      return this.$util.enumFormatter(this.reasonOptions, row.includeType)
    },
    uploadCallback(res, file) {
      if (res.code === 0) {
        this.$router.push({ path: '/abnormal/company/inclusion/accept', query: { tasklistid: res.data.tasklistid, bizseq: res.data.bizseq, workflowId: res.data.workflowId }})
      } else {
        this.$message.error(res.msg)
      }
    },
    // 模板下载
    downLoadTemp() {
      const name = 'company_list.xls'
      window.open(process.env.NODE_ENV === '"development"' ? `/${name}` : `/aiccs/${name}`)
    },
    handleScroll() {
      var scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop
      if (scrollTop > 80) {
        this.showFixed = true
      } else {
        this.showFixed = false
      }
    },
    selectBlur(e) {
      this.searchForm.reportYear = e.target.value
      // this.$set(this.searchForm, 'reportYear', e.target.value)
    },
    // 启动待办
    startTask() {
      if (this.selection.length === 0) return this.$message.error('请至少选择一个企业以开启待办')
      this.nextLoading = true
      // const batch = 'companyTask' + new Date().getTime()
      // sessionStorage.setItem(batch, JSON.stringify(this.selection))
      // this.$router.push({ path: '/abnormal/company/inclusion/accept', query: { batch: batch }})
      // const { href } = this.$router.resolve({ path: '/abnormal/company/accept', query: { batch: batch }})
      // window.open(href, '_blank')
      let ids = ''
      this.selection.forEach(each => {
        ids += (each.toIncludeId + ';')
      })
      // 判断企业是不是已经在办了
      validateBiz({ toIncludeIds: ids.substring(0, ids.length - 1), entertype: 'company' }).then(res => {
        if (res.data.length > 0) {
          let str = ''
          for (const item of res.data) {
            str += item.entname + item.reason + '；'
          }
          this.$alert(str, '业务重复办理', {
            confirmButtonText: '确定',
            callback: action => {
            }
          })
          this.templateDialog1 = false
          this.nextLoading = false
          return
        }
        saveAbnormalAccept(ids.substring(0, ids.length - 1), 'company').then(res => {
          this.nextLoading = false
          if (res.code === 0) {
            this.$router.push({ path: '/abnormal/company/inclusion/accept', query: { tasklistid: res.data.tasklistid, bizseq: res.data.bizseq, workflowId: res.data.workflowId }})
          // const { href } = this.$router.resolve({ path: '/abnormal/company/inclusion/accept', query: { tasklistid: res.data.tasklistid, bizseq: res.data.bizseq, workflowId: res.data.workflowId }})
          // window.open(href, '_blank')
          } else {
            this.$message.error(res.msg)
          }
        })
      })
      // this.$confirm('是否确认启动待办', '提示').then(() => {
      //   let ids = ''
      //   this.selection.forEach(each => {
      //     ids += (each.pripid + ';')
      //   })
      //   saveAbnormalAccept(ids.substring(0, ids.length - 1), 'company').then(res => {
      //     if (res.code === 0) {
      //       this.$router.push({ path: '/abnormal/company/inclusion/accept', query: { tasklistid: res.data.tasklistid, bizseq: res.data.bizseq, workflowId: res.data.workflowId }})
      //       // const { href } = this.$router.resolve({ path: '/abnormal/company/inclusion/accept', query: { tasklistid: res.data.tasklistid, bizseq: res.data.bizseq, workflowId: res.data.workflowId }})
      //       // window.open(href, '_blank')
      //     } else {
      //       this.$message.error(res.msg)
      //     }
      //   })
      // })
    },
    // 搜索
    search() {
      // 重置
      // if(this.$util.isEmpty(this.searchForm.code) && this.$util.isEmpty(this.searchForm.label)){
      //   this.listType = 'L'
      // }
      this.listType = 'L'
      this.pos = '违法行为'
      this.selection = []
      this.pageParam.customParamMap = this.searchForm
      this.pageParam.customParamMap.level = 0
      this.pageParam.curPage = 1
      this.loadPage()
    },
    clearCustomParamMap() {
      this.pageParam.customParamMap.code = ''
      this.pageParam.customParamMap.label = ''
      // this.pageParam.customParamMap.pageSize = 10
      // this.pageParam.customParamMap.total = 0
      // this.pageParam.customParamMap.curPage = 1
    },
    // 获取大类列表
    getLargeList() {
      this.clearCustomParamMap()
      this.pageParam.customParamMap.level = 0
      // 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.pripid === each.pripid) {
              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.pripid === each.pripid) {
            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.pripid === each.pripid) {
            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
      codeListPageByType(this.pageParam).then(res => {
        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.pripid === selection[j].pripid) {
                this.$refs.multipleTable.toggleRowSelection(each, true)
              }
            }
          }
        })
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-content{
  padding: 10pt;
  margin-bottom: 50px;
  background: #fff;
  .content-header{
    background: white;
    .label-name {
      text-align: right;
      display: inline-block;
      width: 220px;
      font-size: $table-content-font-size;
    }
    .el-select{
      width: calc(100% - 221px) !important;
    }
    .search-input-box{
      display: inline-block;
      width: calc(100% - 220px);
    }
    .search-input{
      cursor: pointer;
      width: 100%;
    }
    .body{
      padding: 20px 0 ;
      border-top:none;
      margin-bottom: 40px;
    }
  }
  .content-body{
    background:white;
    margin-bottom: 100px;
  }
  .header{
    /* height: 50PX;
    padding: 15px 10PX; */
    .title{
      font-weight: 600;
      font-size: 1.2rem;
    }
  }
  .page-box{
    margin:10PX;
    .el-pagination{
      text-align: right;
    }
  }
  .prompt{
    color: #F53633;
  }
.fixed-bottom {
  position: fixed;
  width: 100%;
  bottom: -10px;
  right: 0;
  z-index: 99;
  padding: 10px;
  /* background: #8bbef6; */
  border-radius: 5px 5px 0 0;
  background: linear-gradient(to bottom, #fff 0%,#8bbef6 100%);
  box-shadow:  1px -4px 4px rgba(0, 21, 41, 0.08);
}
.content-body{
  background: #fff;
  /deep/.el-table .warning-row {
    background: #eaf4fe!important;
  }
}

}
</style>
