<template>
  <div class="main-content cancelList m20">

    <div class="search-box">
      <el-row class="mb10">
        <el-col :span="6" class="display-flex">
          <label class="label-name">监管所: </label>
          <div>
            <el-select
              v-model="searchForm.paramMap.supOrg"
              placeholder="请选择"
              clearable
              style="width: 100%"
              value-key="value"
              @change="searchOrgEvent"
            >
              <el-option
                v-for="item in supOrgList"
                :key="item.orgNumber"
                :label="item.orgUnitName"
                :value="item.orgNumber" />
            </el-select>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="content-body">
      <el-row v-show="selectionData.length > 0">
        <el-col :span="4" :offset="20">
          <el-button type="primary" size="mini" @click="batchHandleOrgEvent">批量指派监管所</el-button>
          <el-button type="primary" size="mini" @click="batchHandlePeopleEvent">批量指派人员</el-button>
        </el-col>
      </el-row>
      <div class="body">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          tooltip-effect="dark"
          class="table-style"
          :fit="true"
          :row-class-name="tableRowClassName"
          @selection-change="selectionChangeHandle"
          :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
          @sort-change="sortChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="index" label="序号" min-width="30" align="center" />
          <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="120" align="left">
            <template slot-scope="scope">
              <router-link
                style="color: #409EFF"
                :to="{path:'/comprehensive/details',query:{ pripid: scope.row.pripid }}"
              >
                {{ scope.row.uscc }}
              </router-link>
            </template>
          </el-table-column>
          <el-table-column prop="entName" :show-overflow-tooltip="true" label="主体名称" min-width="180" align="left" />
          <el-table-column prop="supOrgCn" :show-overflow-tooltip="true" label="属地监管所" :formatter="orgCnFormatter" min-width="80" align="left" />
          <el-table-column prop="orgCn" :show-overflow-tooltip="true" label="任务来源" :formatter="orgCnFormatter" min-width="80" align="left" />
          <el-table-column prop="remarks" :show-overflow-tooltip="true" label="备注" min-width="100" align="left" />
          <el-table-column label="操作" min-width="180">
            <template slot-scope="scope">
              <el-button v-show="scope.row.status === '0'" type="primary" size="mini" @click="showDialogEvent(scope.row, '0')">指派监管所</el-button>
              <el-button v-show="scope.row.status === '0' || (scope.row.status === '1' && scope.row.sendOrg === user.orgCode)" type="primary" size="mini" @click="showDialogEvent(scope.row, '1')">指派人员</el-button>
              <el-button v-show="scope.row.status === '3'" type="primary" size="mini" @click="dynamicSupervisionEvent(scope)">查看现场核查结果</el-button>
              <el-button type="primary" size="mini" @click="downFile(scope.row)">现场核查通知书</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-box">
          <el-row>
            <el-col :span="6" />
            <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"
              >
                <span>
                  第 {{ pageParam.curPage }} 页 /
                  共 {{ (pageParam.total !== 0 ? parseInt((pageParam.total + pageParam.pageSize - 1)/pageParam.pageSize) : 1) }} 页
                </span>
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <el-dialog width="30vw" :close-on-click-modal="false" :visible.sync="showDialog" size="mid" :title="dialogTitle">
      <el-row>
        <el-col>
          <el-select
            v-if="isShowOrg"
            v-model="sendOrg"
            placeholder="请选择"
            clearable
            style="width: 100%"
            value-key="value"
          >
            <el-option
              v-for="item in supOrgList"
              :key="item.orgNumber"
              :label="item.orgUnitName"
              :value="item.orgNumber"
            />
          </el-select>

          <el-select
            v-else
            v-model="sendUserId"
            placeholder="请选择"
            clearable
            style="width: 100%"
            value-key="value"
          >
            <el-option
              v-for="item in userList"
              :key="item.primaryKey"
              :label="item.name"
              :value="item.primaryKey"
            />
          </el-select>
        </el-col>
      </el-row>

      <el-row>
        <el-col style="padding-top: 10px" :offset="11">
          <el-button type="primary" size="mini" @click="updateEvent()">派送</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog
      :visible.sync="inputDialog.visible"
      title="检查情况"
      width="80vw"
      :append-to-body="true"
      :modal-append-to-body="true"
    >
      <EasyForm
        ref="inputDialog"
        v-model="inputDialog.formData"
        v-loading="inputDialog.loading"
        :fields="dynamicSupervisionFields"
        :form-config="inputDialog.config"
        :buttons="inputDialog.buttons"
        @cancel="inputDialog.visible = false"
      >
        <div slot="actualScope" slot-scope="scope" style="display: flex;">
          <el-input v-model="scope.formData.actualScope" disabled style="margin-right: 10px" />
          <el-button type="primary">选择</el-button>
        </div>
        <div slot="opinion" slot-scope="scope">
          <el-input
            v-model="scope.formData.opinion"
            type="textarea"
            :rows="2"
          />
        </div>
      </EasyForm>
    </el-dialog>
  </div>
</template>

<script>
import { getSupOrg, tFraudCheckList, updateFraudCheckList, batchUpdateTFraudCheck } from '@/api/personate'
import { listAttachmentByModelParam } from '@/api/attachment'
import { getSameDeptUserList } from '@/api/user'
import { getUsualInspectInfo, tSUsualInspectListFile } from '@/api/market'
import EasyForm from '@/components/EasyForm'
import dynamicSupervisionBase from '@/views/market/dynamicsupervision/index'

export default {
  data() {
    return {
      user: JSON.parse(sessionStorage.getItem('user')),
      item: null,
      showDialog: false,
      showType: false,
      isBatchHandle: false,
      sendOrg: '',
      sendUserId: '',
      resultForm: {},
      supOrgList: [],
      userList: [],
      searchForm: {
        orderField: '',
        orderingRule: '',
        paramMap: {
          supOrg: ''
        },
        likeParamMap: {},
        customParamMap: {}
      },
      loading: false,
      tableData: [],
      selectionData: [],
      inputDialog: {
        config: {
          readOnly: true
        }
      },
      pageParam: {
        curPage: 1,
        total: 0,
        pageSize: 10
      }
    }
  },
  computed: {
    // 是否显示机关所
    isShowOrg() {
      return this.showType === '0'
    },
    dialogTitle() {
      return this.showType === '0' ? '选择监管所' : '分派人员'
    }
  },
  mounted() {
    this.search()
    this.initSupOrg()

    // 获取监管所人员
    getSameDeptUserList('').then(res => {
      this.userList = res.data
    })
  },
  methods: {
    downFile(row) {
      let file = {}
      listAttachmentByModelParam({ bizseq: row.bizSeq, attachtype: '4' }).then(data => {
        if (data.length > 0) {
          data.forEach(each => {
            each.id = each.attachmentid
            each.name = each.filename
            each.url = `${process.env.VUE_APP_DOWNLOAD_URL}/` + each.temppath
          })
          file = data[0]
          window.open(file.url, '_blank')
        } else {
          this.$message.error('无可下载文件')
        }
      })
    },
    updateEvent() {
      if (!this.isBatchHandle) {
        const data = {
          ...this.item,
          sendOrg: this.sendOrg,
          sendUserId: this.sendUserId,
          status: this.isShowOrg ? '1' : '2'
        }
        updateFraudCheckList(data).then(() => {
          this.showDialog = false
          this.item = null
          this.search()
        })
      } else { // 批量更新
        const dataList = this.selectionData.map((o) => {
          return {
            ...o,
            sendOrg: this.sendOrg,
            sendUserId: this.sendUserId,
            status: this.isShowOrg ? '1' : '2'
          }
        })
        batchUpdateTFraudCheck(dataList).then(() => {
          this.showDialog = false
          this.isBatchHandle = false
          this.selectionData = []
          this.search()
        })
      }
    },
    showDialogEvent(row, type) { // type 0-监管所 1-人员
      this.showType = type
      this.showDialog = true
      if (row !== null) {
        this.item = row
        this.sendOrg = row.sendOrg
        this.sendUserId = row.sendUserId
      }
    },
    initSupOrg() {
      getSupOrg().then(res => {
        this.supOrgList = res.data.filter(item => item.orgLevel === 4 && item.unitType === '1')
      })
    },
    orgCnFormatter(row, column, cellValue, index) {
      return cellValue.replace(new RegExp('广州市', 'g'), '').replace(new RegExp('市场监督管理局', 'g'), '')
    },
    searchOrgEvent(val) {
      this.search()
    },
    // 批量指派监管所 v-show="scope.row.status === '0'"
    batchHandleOrgEvent() {
      if (this.selectionData.filter((item) => item.status !== '0').length > 0) {
        this.$message.error('无法批量操作')
      } else {
        this.isBatchHandle = true
        this.showDialogEvent(null, '0')
      }
    },
    // 批量指派监管所 v-show="scope.row.status === '0' || (scope.row.status === '1' && scope.row.sendOrg === user.orgCode)"
    batchHandlePeopleEvent() {
      if (this.selectionData.filter((item) => item.status === '0' || (item.status === '1' && item.sendOrg === this.user.orgCode)).length !== this.selectionData.length) {
        this.$message.error('无法批量操作')
      } else {
        this.isBatchHandle = true
        this.showDialogEvent(null, '1')
      }
    },
    selectionChangeHandle(val) {
      this.selectionData = val
    },
    sortChange({ column, prop, order }) {
      this.searchForm.orderField = prop
      this.searchForm.orderingRule = order === 'ascending' ? 'asc' : 'desc'
      this.search()
    },
    // 搜索
    search() {
      this.pageParam.paramMap = {
        paramMap: {},
        likeParamMap: {},
        customParamMap: {}
      }
      for (const key in this.searchForm) {
        if (typeof this.searchForm[key] === 'string') {
          this.pageParam.paramMap[key] = this.searchForm[key]
        } else {
          for (const _key in this.searchForm[key]) {
            if (this.searchForm[key][_key]) {
              if (!this.pageParam.paramMap[key]) {
                this.pageParam.paramMap[key] = {}
              }
              this.pageParam.paramMap[key][_key] = this.searchForm[key][_key]
            }
          }
        }
      }
      this.pageParam.curPage = 1
      this.loadPage()
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    // 当前分页改变
    pageIndexChange(curPage) {
      this.pageParam.curPage = curPage
      this.loadPage()
    },
    // 分页大小改变
    pageSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize
      this.loadPage()
    },
    // 加载分页
    loadPage() {
      if (this.loading) return
      this.loading = true
      const data = JSON.parse(JSON.stringify({
        ...this.pageParam,
        ...this.pageParam.paramMap
      }))
      tFraudCheckList(data).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
      })
    },
    dynamicSupervisionEvent(scope) {
      this.item = scope.row
      this.inputDialog.visible = true
      this.inputDialog.loading = true

      getUsualInspectInfo(scope.row.inspectId).then(res => {
        const inspectInfo = res.data

        tSUsualInspectListFile({ id: scope.row.inspectId }).then((res) => {
          const { code, data } = res
          if (code !== 0) {
            throw res
          }
          this.inputDialog.formData = {
            ...inspectInfo,
            files: []
          }
          this.$set(this.inputDialog.formData, 'files', data.filter((file) => {
            return file.attachtype === '2'
          }).map((item) => {
            return {
              ...item,
              name: item.filename
            }
          }))
          this.$set(this.inputDialog.formData, 'files0', data.filter((file) => {
            return file.attachtype === '1'
          }).map((item) => {
            return {
              ...item,
              name: item.filename
            }
          }))
        }).finally(() => {
          this.inputDialog.loading = false
        })
      }).finally(() => {
        this.inputDialog.loading = false
      })
    }
  },
  components: {
    EasyForm
  },
  mixins: [dynamicSupervisionBase]
}
</script>
<style lang="scss" scoped>
.search-box {
  padding: 20px;
  .search-field {
    display: inline-block;
    width: 100%;
    align-items: center;
    > p {
      width: 190px;
      text-align: right;
      display: inline-block;
      margin: 0 0 10px 0;
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      color: #5e5e7a;
      font-size: 16PX;
    }
  }
  .mb10 {
    margin-bottom: 10px;
  }

}
.search-body{
  .el-col{
    display: flex;
    align-items: baseline;
  }
}
.main-content.cancelList{
  background: #fff;
  padding: 10px;
  .content-header{
    background: white;
    .label-name_1 {
      text-align: right;
      display: inline-block;//转成行内快，才可定义宽度
      width: 220px;
      font-size: $table-content-font-size;
    }
    .search-input-box_1{
      display: inline-block;
      width: calc(100% - 220px);
    }
    .label-name_2 {
      text-align: right;
      display: inline-block;//转成行内快，才可定义宽度
      width: 220px;
      font-size: $table-content-font-size;
    }
    .search-input-box_2{
      display: inline-block;
      width: calc(100% - 220px);
    }
    .label-name_3 {
      text-align: right;
      display: inline-block;//转成行内快，才可定义宽度
      width: 220px;
      font-size: $table-content-font-size;
    }
    .label-name {
      font-size: $table-content-font-size;
    }
    .search-input-box_3{
      display: inline-block;
      width: calc(100% - 220px);
    }
    .search-input{
      cursor: pointer;
    }
    .body{
      padding: 20px 0 ;
      border-top:none;
      margin-bottom: 40PX;
    }
  }
  .content-body{
    background:white;
  }
  .header{
    /* height:50px; */
    /* padding:15PX 10PX; */
    /* border:1PX solid #eee; */
    .title{
      font-weight: 600;
      font-size: 1.2rem;
    }
  }
  .page-box{
    margin:10PX;
    .el-pagination{
      text-align: right;
    }
  }
    .el-form-item{
    margin-bottom:0;
    background: $color-form-label;
    .el-form-item__label{
        padding-left: 10px;
        border-top: 1px solid $color-border;
        border-left: 1px solid $color-border;
    }
    .el-form-item__content{
        .span{
          display: inline-block;
        }
        background: white;
        padding: 10px;
        border-top: 1px solid $color-border;
        border-right: 1px solid $color-border;
        border-left: 1px solid $color-border;
    }
  }
  .dialog_content{
    max-height: 600px;
    overflow-x: auto;
    padding-left: 5px;
    padding-top: 5px;
      .el-row{
          border-top: 1px solid $color-border;
      }
    .tab{
        .tab-title{
          margin-top: 20px;
          label{
            background: $color-primary;
            display:inline-block;
            color:$color-title-color;
            padding:10px 20px 10px 5px;
          }
        }
      }
  }
  .dialog-box{
    padding-right: 20px;
    text-align: right;
  }
  .last_row{
      border-bottom: 1px solid $color-border;
  }
  .custom{
      width: 100%;
  }
  .span-content{
    display: block;
    text-indent: 1em;
  }
}
.content-body{
  background: #fff;
  /deep/.el-table .warning-row {
    background: #eaf4fe!important;
  }
}
.flex-content{
  /deep/ .el-form-item__content{
    display: flex;
  }
}
.content-body{
  background: #fff;
  /deep/.el-table .warning-row {
    background: #eaf4fe!important;
  }
  /deep/.el-table .sort-caret.descending{
    border-top-color:#fff!important;
  }
  /deep/.el-table .sort-caret.ascending{
    border-bottom-color:#fff!important;
  }
}
</style>
