<template>
  <div class="main-content abnormal">
    <!-- <div class="content-header">
      <span class="title">经营异常名录列入：经办</span>
      <el-button type="warning" icon="el-icon-caret-left" size="mini" class="back-btn" @click="$router.back()">返回上一层</el-button>
    </div> -->
    <!-- <DetailHead /> -->
    <div class="content-body">
      <el-form ref="form" :model="form" label-width="180px" label-position="right" :rules="formRules">
        <div class="form">
          <div class="tab">
            <div class="tab-title"><label>异常信息</label></div>
          </div>
          <div class="form-body">
            <el-row class="lh0">
              <el-form-item label="列入异常主体信息">
                <el-button size="medium" type="primary" @click="showEntbaseList">查看异常主体名单<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
                <el-button size="medium" type="primary" @click="exportEntListExcel">导出Excel<i class="el-icon" style="margin-left:5px" /></el-button>
                <el-button v-if="remList.length > 0" size="medium" type="primary" @click="showRemEntList">查看已剔除名单<i class="el-icon el-icon-s-order" style="margin-left:5px" /></el-button>
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item label="列入原因" prop="reason" class="bt0">
                <el-col :span="24">
                  <el-select v-model="reason" style="width:100%" placeholder="请选择列入原因" class="custom">
                    <el-option
                      v-for="item in reasonOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-col>
                <!-- <el-input v-model="form.reason" type="textarea" placeholder="请输入列入原因" disabled /> -->
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item label="决定书内容" prop="decisionContent" class="bt0">
                <el-col :span="24">
                  <el-input v-model="decisionContent" style="width:100%" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item label="备注" prop="remark" class="bt0">
                <el-col :span="24">
                  <el-input v-model="remark" type="textarea" placeholder="备注" style="width:100%" :autosize="{ minRows: 3, maxRows: 6 }" maxlength="500" show-word-limit />
                </el-col>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="材料上传" class="upload bt0">
                <el-upload
                  :action="uploadPath"
                  :data="{bizseq:bizseq}"
                  :on-remove="removeFile"
                  :on-success="uploadCallback"
                  :on-preview="previewFile"
                  :before-upload="beforeFileUpload"
                  :before-remove="beforeRemove"
                  accept=".doc,.docx,.xlsx,.xls,.pdf,.jpg,.zip,.rar,.7z"
                  multiple
                  :file-list="fileList"
                  style="max-width:800px;display: inline-block"
                  class="uploadFileList"
                >
                  <div style="display: inline-block;">
                    <el-button size="medium" style="display: inline-block;margin-right:10px" type="primary">点击上传</el-button>
                    <div slot="tip" style="display: inline-block;" class="el-upload__tip">只能上传jpg/png/pdf/doc/docx/xls/xlsx/rar/zip/7z文件，且单个文件不能超过20M</div>
                  </div>
                </el-upload>
              </el-form-item>
            </el-row>

          </div>
        </div>
        <div class="form">
          <div class="tab">
            <div class="tab-title"><label>处理意见</label></div>
          </div>
          <div class="form-body history">
            <div v-if="historyLog.length == 0" class="none">暂无处理意见</div>
            <el-steps direction="vertical">
              <el-step v-for="(each,index) in historyLog" :key="'historyLog'+index" :title="each.step + '人：' + each.handler + ' ' + each.step +'日期：' + each.handledate " :description=" each.opinioncontent " status="finish" />
            </el-steps>
          </div>
        </div>
        <div class="form">
          <div class="tab">
            <div class="tab-title"><label>经办意见</label></div>
          </div>
          <div class="form-body">
            <el-row>
              <el-form-item label="经办意见" prop="opinion">
                <el-col :span="24">
                  <el-input v-model="form.opinion" type="textarea" placeholder="请输入经办意见" :autosize="{ minRows: 2, maxRows: 6 }" />
                </el-col>
                <el-col :span="12">
                  <label style="line-height:32px">常用语</label>
                  <el-select v-model="opinion" clearable placeholder="请选择" class="custom" style="width:100%">
                    <el-option
                      v-for="item in opinionOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-col>
              </el-form-item>
            </el-row>

            <el-row>
              <el-form-item label="审核人" prop="reviewerId" class="bt0">
                <el-col :span="12">
                  <el-select v-model="form.reviewerId" style="width:100%" filterable clearable placeholder="请选择审核人" class="custom">
                    <el-option
                      v-for="item in reviewer"
                      :key="'reviewer'+item.primaryKey"
                      :label="item.name"
                      :value="item.primaryKey"
                    />
                  </el-select>
                </el-col>
              </el-form-item>
            </el-row>

          </div>
        </div>
      </el-form>
      <div class="submit-box">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">提交</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </div>
    </div>
    <el-dialog
      title="异常主体名单"
      :visible.sync="showEntbase"
      width="90%"
    >
      <el-table
        v-loading="loading"
        :data="bizList"
        tooltip-effect="dark"
        style="width: 100%; min-height: 380px"
        :fit="true"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column class="no" type="selection" min-width="20" align="center" />
        <el-table-column prop="index" label="序号" min-width="50" align="center" />
        <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="160" align="left" />
        <el-table-column prop="entname" :show-overflow-tooltip="true" label="名称" min-width="150" align="left" />
        <el-table-column prop="address" :show-overflow-tooltip="true" label="经营地址" min-width="150" align="left" />
        <el-table-column prop="estDate" :show-overflow-tooltip="true" label="成立时间" min-width="90" align="left" />
        <el-table-column prop="lerepname" label="法定代表人" align="left" />
        <el-table-column prop="entTypeName" :show-overflow-tooltip="true" label="主体类型" min-width="100" align="left" />
        <el-table-column prop="regstateCn" :show-overflow-tooltip="true" label="主体状态" min-width="120" align="left" />
      </el-table>
      <template v-if="this.multipleSelection.length > 0">
        <el-row style="margin-bottom: 5px;margin-top:2px;border: unset">
          <label style="float: left;margin-left:10px;font-size:16px">剔除原因：</label>
          <el-input v-model="removeReason" style="width: 90%;" :autosize="{ minRows: 1 }" type="textarea" />
        </el-row>
      </template>
      <div>
        <el-row class="bl0">
          <el-col :span="12">
            <el-pagination
              :current-page="pageParam.curPage"
              small
              layout="prev, pager, next"
              :total="pageParam.total"
              @size-change="pageSizeChange"
              @current-change="pageIndexChange"
            />
          </el-col>
          <el-col :span="12">
            <div class="dialog-box">
              <el-button type="danger" size="mini" @click="removeEntbaseItem">剔除</el-button>
              <el-button type="primary" size="mini" @click="showEntbaseList">确定</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog
      title="已剔除主体名单"
      :visible.sync="showRemEnt"
      width="90%"
    >
      <el-table
        v-loading="loading"
        :data="remList"
        tooltip-effect="dark"
        style="width: 100%; min-height: 380px"
        :fit="true"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="index" label="序号" min-width="50" align="center" />
        <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="160" align="left" />
        <el-table-column prop="entname" :show-overflow-tooltip="true" label="主体名称" min-width="210" align="left" />
        <el-table-column prop="removeReason" :show-overflow-tooltip="true" label="剔除原因" min-width="180" align="left" />
        <el-table-column
          prop="removeTime"
          :show-overflow-tooltip="true"
          label="剔除时间"
          min-width="80"
          align="left"
        />
        <el-table-column prop="removeHandler" label="剔除处理人" min-width="80" align="left" />
      </el-table>
      <div>
        <el-row class="bl0">
          <el-col :span="12">
            <el-pagination
              :current-page="remPageParam.curPage"
              small
              layout="prev, pager, next"
              :total="remPageParam.total"
              @size-change="remPageSizeChange"
              @current-change="remPageIndexChange"
            />
          </el-col>
          <el-col :span="12">
            <div class="dialog-box">
              <el-button type="primary" size="mini" @click="showRemEntList">确定</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DetailHead from '@/components/DetailHead'
import HandleDialog from '@/components/HandleDialog'
import { removeAttachementById, listAttachmentByBizseq } from '@/api/attachment'
import { nextAbnormaInclusionProcess, getBizSpeListPage, removeBySpelistid } from '@/api/abnormal'
import { getUsersWithPermission, getUsersPermission } from '@/api/user'
import { getConstant } from '@/api/system'
import { validBeforeUpload } from '@/api/fileUpload'
import { parseTime } from '@/utils'
import { taskOpinion } from '@/api/task'
import { isMenHu } from '@/utils/utils'

export default {
  components: {
    HandleDialog: HandleDialog,
    DetailHead
  },
  data() {
    return {
      remPageParam: {
        customParamMap: {
          bizseq: '',
          searchCode: '',
          entname: '',
          type: 'rem'
        },
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      remList: [],
      showRemEnt: false,
      removeReason: '',
      decisionContent: '',
      prepareContent: '',
      submitLoading: false,
      remark: '',
      uploadPath: `${process.env.VUE_APP_BASE_API}/attachment/uploadAdvance`,
      showEntbase: false,
      bizseq: '',
      workflowId: '',
      tasklistid: '',
      entbase: [], // 主体名单列表
      // 分页数据,这里用来保存每页切割后的数据
      // 看起来格式是这样的[[{},{},{}],[{},{},{}]]
      // 数组内套数组，每个数组就是一页数据
      totalPageData: [],
      // 共几页
      pageNum: '',
      // 每页显示数量
      pageSize: 10,
      // 当前显示页码
      currentPage: 1,
      // 总共多少条数据
      total: 1,
      // 当前要显示的数据
      dataShow: [],
      // 选中数组
      multipleSelection: [],
      form: {
        enterType: 'farmer',
        spereasons: '',
        reason: '',
        remark: '',
        opinion: ''
      },
      formRules: {
        reason: [
          { required: true, message: '请输入列入原因', trigger: 'blur' }
        ],
        opinion: [
          { required: true, message: '请输入经办意见', trigger: ['blur', 'change'] }
        ],
        reviewerId: [
          { required: true, message: '请选择后续处理人' }
        ]
      },
      reason: '',
      opinion: '',
      reasonOptions: [],
      opinionOptions: [{
        value: 0,
        label: '拟同意，呈领导审核。'
      }],
      historyLog: [],
      exmainerOptions: [],
      fileList: [],
      user: JSON.parse(sessionStorage.getItem('user')),
      reviewer: [],
      pageParam: {
        customParamMap: {
          bizseq: '',
          searchCode: '',
          entname: '',
          type: 'biz'
        },
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      bizList: [], // 异常主体名单分页列表
      loading: false
    }
  },
  watch: {
    // 原因渲染
    reason() {
      this.form.specause = this.reason
      let name = ''
      this.reasonOptions.forEach(each => {
        if (this.reason === each.value) {
          name = each.label
        }
      })
      this.form.reason = name
      if (this.reason === '1') {
        this.prepareContent = '经查，你单位因' + name + '，根据《农民专业合作社年度报告公示暂行办法》第十条的规定，我局决定将你单位列入经营异常名录，并向社会公示。'
      } else if (this.reason === '2') {
        this.prepareContent = '经查，你单位因' + name + '，根据《农民专业合作社年度报告公示暂行办法》第十一条的规定，我局决定将你单位列入经营异常名录，并向社会公示。'
      } else if (this.reason === '3') {
        this.prepareContent = '经查，你单位因' + name + '，根据《农民专业合作社年度报告公示暂行办法》第十二条的规定，我局决定将你单位列入经营异常名录，并向社会公示。'
      }
      this.decisionContent = this.prepareContent
    },
    // 意见渲染
    opinion() {
      let name = ''
      this.opinionOptions.forEach(each => {
        if (this.opinion === each.value) {
          name = each.label
        }
      })
      this.form.opinion = name
    }
  },
  mounted() {
    this.bizseq = this.$route.query.bizseq // 获取跳转携带的参数bizseq
    this.workflowId = this.$route.query.workflowId
    this.tasklistid = this.$route.query.tasklistid
    // 加载常用语 农专社经营异常名录列入
    this.opinionOptions = this.$util.getCommonWordsWithModule(this.user.primaryKey, '农专社经营异常名录列入')
    // 加载农庄列入原因(trbasecode表 'CD77')
    getConstant('CD77').then(res => {
      if (res.code === 0) {
        const list = []
        res.data.forEach(each => {
          list.push({
            value: each.code,
            label: each.name
          })
        })
        this.reasonOptions = list
      }
    })
    // 加载异常名录主体
    this.loadBizSpeListPage()
    this.loadRemListPage()
    // listAbnormalByBizSeq(this.bizseq).then(res => {
    //   if (res.code === 0) {
    //     // 添加分页index
    //     let i = 1
    //     const pageStart = (this.currentPage - 1) * this.pageSize
    //     res.data.forEach(each => {
    //       each.index = pageStart + i++
    //       each.name = each.entname
    //       each.uscc = each.regno
    //       each.typeName = each.entTypeName
    //       // this.$set(this, 'reason', each.specause)
    //       this.entbase.push(each)
    //     })
    //     this.reason = this.entbase[0].specause
    //     this.remark = this.entbase[0].remark === 'null' ? '' : this.entbase[0].remark
    //     if (this.entbase[0].decisionContent !== null) {
    //       this.$nextTick(() => {
    //         this.decisionContent = this.entbase[0].decisionContent
    //       })
    //     }
    //     // 分页处理
    //     this.total = this.entbase.length
    //     // 计算页数
    //     this.calcPageData()
    //   } else {
    //     this.$message.error('加载异常名录主体信息失败')
    //   }
    // })
    // 加载处办记录
    taskOpinion(this.workflowId).then(res => {
      if (res.code === 0) {
        res.data.forEach(each => {
          switch (each.opiniontype) {
            case '0': each.step = '经办'; break
            case '1': each.step = '审核'; break
            case '2': each.step = '审批'; break
          }
          this.historyLog.push(each)
        })
      } else {
        this.$message.error('加载办理记录失败')
      }
    })

    // 加载审核人
    this.loadReviewer()

    // 加载附件清单
    listAttachmentByBizseq(this.bizseq).then(data => {
      const list = []
      data.forEach(each => {
        if (each.attachtype !== '0') {
          each.id = each.attachmentid
          each.name = each.filename
          each.url = `${process.env.VUE_APP_DOWNLOAD_URL}/` + each.temppath
          list.push(each)
        }
      })
      this.fileList = list
    })
  },
  methods: {
    loadBizSpeListPage() {
      if (this.loading) return
      this.loading = true
      this.pageParam.customParamMap.bizseq = this.bizseq
      getBizSpeListPage(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++
          each.uscc = each.uniscid ? each.uniscid : each.regno
          list.push(each)
        })
        this.bizList = list
        this.loading = false
        this.pageParam.total = res.data.total
        this.reason = this.bizList[0].specause
        this.remark = this.bizList[0].remark === 'null' ? '' : this.bizList[0].remark
        if (this.bizList[0].decisionContent !== null) {
          this.$nextTick(() => {
            this.decisionContent = this.bizList[0].decisionContent
          })
        }
        const selection = JSON.parse(JSON.stringify(this.multipleSelection))
        this.$nextTick(() => {
          for (const i in list) {
            const each = list[i]
            for (const j in selection) {
              if (each.pripid === selection[j].pripid) {
                this.$refs.bizList.toggleRowSelection(each, true)
              }
            }
          }
        })
      })
    },
    // 加载已剔除名单
    loadRemListPage() {
      this.loading = true
      this.remPageParam.customParamMap.bizseq = this.bizseq
      getBizSpeListPage(this.remPageParam).then((res) => {
        const list = []
        let i = 1
        const pageStart =
          (this.remPageParam.curPage - 1) * this.remPageParam.pageSize
        res.data.records.forEach((each) => {
          each.index = pageStart + i++
          each.uscc = each.uniscid ? each.uniscid : each.regno
          list.push(each)
        })
        this.remList = list
        this.loading = false
        this.remPageParam.total = res.data.total
      })
    },
    // 剔除名单列表分页大小改变
    remPageSizeChange(pageSize) {
      this.remPageParam.pageSize = pageSize
      this.loadRemListPage()
    },
    // 剔除名单列表当前分页改变
    remPageIndexChange(curPage) {
      this.remPageParam.curPage = curPage
      this.loadRemListPage()
    },
    parseTime(...args) {
      return parseTime(...args)
    },
    // 分页大小改变
    pageSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize
      this.loadBizSpeListPage()
    },
    // 当前分页改变
    pageIndexChange(curPage) {
      this.pageParam.curPage = curPage
      this.loadBizSpeListPage()
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    // 主体名单导出Excel
    exportEntListExcel() {
      this.$confirm('是否确认导出', '提示').then(() => {
        const url = location.origin + process.env.VUE_APP_BASE_API + '/bizSpeList/exportEntList?bizseq=' + this.bizseq
        window.open(url)
      })
    },
    // 上传文件之前校验大小
    beforeFileUpload(file) {
      var that = this
      return validBeforeUpload(file, that)
    },
    // 移除文件前
    beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name} ？`)
      }
    },
    // 剔除主体名单
    removeEntbaseItem() {
      if (this.multipleSelection.length === 0) return this.$message.warning('请至少选择一个企业从此列表中剔除')
      if (this.$util.isEmpty(this.removeReason)) return this.$message.warning('请输入剔除原因')
      this.$confirm('是否确认剔除', '提示').then(() => {
        // 遍历获取spelistid 拼接成字符串形式
        let ids = ''
        this.multipleSelection.forEach(each => {
          ids += (each.spelistid + ';')
        })
        // 调接口
        removeBySpelistid(ids.substring(0, ids.length - 1), this.removeReason, this.bizseq).then(res => {
          if (res.code === 0) {
            this.loadBizSpeListPage()
            this.loadRemListPage()
            this.$message.success('剔除成功')
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 上传文件预览
    previewFile(file) {
      window.open(file.url, '_blank')
    },
    // 发送提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.$confirm('是否确认发送？', '提示').then(() => {
          this.submitLoading = true
          this.form.bizseq = this.bizseq
          this.form.workflowid = this.workflowId
          this.form.opiniontype = '0'
          this.form.handler = this.user.username
          this.form.handlerid = this.user.primaryKey
          this.form.opinioncontent = this.form.opinion
          this.form.tasklistid = this.tasklistid
          this.form.remark = this.remark
          this.form.decisionContent = this.decisionContent
          this.form.nextPerformerids = this.form.reviewerId
          for (const i in this.reviewer) {
            if (this.reviewer[i].primaryKey === this.form.reviewerId) {
              this.form.nextPerformerNames = this.reviewer[i].name
            }
          }
          this.form.nextNodeID = 'handleExptlist'
          nextAbnormaInclusionProcess(this.form).then(res => {
            this.submitLoading = false
            if (res.code === 0) {
              this.$message.success('提交成功')
              if (isMenHu()) {
                // 信创门户环境跳转回待办
                window.location.href = '/aiccs/#/todo/list'
              } else {
                this.$router.back()
              }
            }
          })
        }).catch(() => {})
      })
    },
    uploadCallback(res, file) {
      if (res.code === 0) {
        file.id = res.data.attachmentid
      }
    },
    // 查看异常主体名单
    showEntbaseList() {
      this.showEntbase = !this.showEntbase
    },
    // 查看已剔除主体名单
    showRemEntList() {
      this.showRemEnt = !this.showRemEnt
    },
    // 移除文件回调
    removeFile(file) {
      if (file && file.status === 'success') {
        removeAttachementById(file.id).then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功')
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    // 加载审核人
    loadReviewer() {
      return getUsersPermission('agricultureInclusionReview', this.user.orgId, this.bizseq).then(res => {
        if (res.code === 0) {
          this.reviewer = res.data
        }
      })
    }
    // loadReviewer() {
    //   getUsersWithPermission('agricultureInclusionReview', this.user.orgId).then(res => {
    //     if (res.code === 0) {
    //       this.reviewer = res.data
    //     }
    //   })
    // }
  }
}
</script>

<style lang="scss" scoped>
.main-content{
  font-size: $table-content-font-size;
  .back-btn{
    position:absolute;
    right:40pt;
  }
  .content-header,.content-body{
    background: white;
    padding:20PX 10PX;
    border:1PX solid #eee;
  }
  .content-header{
    height:60PX;
    .title{
      font-weight: 700;
      font-size: $font-size-sub-title;
    }
  }
  .content-body{
    padding:20pt;
      .tab{
        .tab-title{
          label{
            display:inline-block;
          }
        }
      }
    .form{
      margin-bottom: 20pt;
    }
  }
}
.el-row {
  border-left: 1px solid $color-border;
}
.bt0 {
  /deep/.el-form-item__label{
    border-top: 0!important;
  }
  /deep/.el-form-item__content{
    border-top: 0!important;
  }
}
</style>
<style lang="scss">
.main-content.abnormal{
  .el-form-item{
    margin-bottom:0;
    background: $color-form-label;
    .el-form-item__label{
      padding-left: 10px;
      font-size: $table-content-font-size;
      border-top: 1px solid $color-border;
    }
    .el-form-item__content{
      background: white;
      padding: 10px;
      font-size: $table-content-font-size;
      border-top: 1px solid $color-border;
      border-right: 1px solid $color-border;
      border-left: 1px solid $color-border;
    }
  }
  .el-form-item:last-child{
    border-bottom: 1px solid $color-border;
  }
  .form-body.history{
    padding:15px;
    border:1px solid $color-border;
  }
  .el-form-item.is-error .custom .el-input__inner{
    border-color:$color-border;
  }
  .el-table-column--selection .cell {
    padding-right: 0px;
  }
  .no {
    padding-left: 0px;
  }
  .el-table_9_column_61.is-left.is-leaf{
    .cell{
      padding-left: 0px;
      padding-right: 0px;
    }
  }
  .dialog-box{
    text-align: right;
  }
  .el-textarea.is-disabled .el-textarea__inner{
    color: #1c1e23;
  }
  .el-input__inner{
    margin-bottom: 5px;
  }
  .uploadFileList{
    .el-upload-list__item{
      display: inline-block;
      width: auto;
    }
  }
  .el-step__description{
    font-size: 18px;
  }
}
</style>
