<template>
  <div class="main-content market m20">
    <searchHeader title="查询" />
    <div class="search-box">
      <el-row>
        <el-col :span="6">
          <label class="label-name" style="width: 90px;display: inline-block;">片区名称:</label>
          <div class="search-input-box" style="width: calc(100% - 100px);display: inline-block;">
            <el-input v-model="searchForm.sliceName" placeholder="请输入搜索片区名称" @keyup.native.enter="search" />
          </div>
        </el-col>
        <el-col :span="6">
          <label class="label-name" style="width: 90px;display: inline-block;">监督人员:</label>
          <div class="search-input-box" style="width: calc(100% - 100px);display: inline-block;">
            <el-input v-model="searchForm.supervisorName" placeholder="请输入监督人员名称" @keyup.native.enter="search" />
          </div>
        </el-col>
        <el-col :span="4">
          <div class="btn-box">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查询</el-button>
            <el-button type="info" icon="el-icon-refresh-left" size="mini" @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="main-body ">
      <div class="header">
        <el-row>
          <el-col :span="24">
            <div class="btn-box">
              <el-button v-if="isSjs" type="primary" icon="el-icon-plus" size="mini" @click="openCreate">新建</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="content">
        <el-table
          v-loading="loading"
          :data="tableData"
          :row-class-name="tableRowClassName"
          :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
          class="table-style"
        >
          <el-table-column
            prop="index"
            label="序号"
            min-width="50"
          />
          <el-table-column
            prop="sliceName"
            label="片区名称"
            min-width="100"
          />
          <el-table-column
            prop="sliceAddr"
            label="地址路段"
            min-width="100"
          />
          <el-table-column
            prop="supervisorName"
            label="监管人员"
            min-width="50"
          />
          <el-table-column
            label="状态"
            min-width="50"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.state === '1'" class="data-state run">启动</span>
              <span v-if="scope.row.state === '0'" class="data-state stop">停用</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="操作"
          >
            <template slot-scope="scope">
              <span v-if="isSjs" >
                <el-link v-if="scope.row.sliceType != '0'" type="primary" style="margin:0 5px" @click="openAMap(scope.row)">{{ scope.row.isInit == '0' ? '描点':'调整围点' }}</el-link>
<!--                <el-link v-if="scope.row.sliceType != '0'" type="primary" style="margin:0 5px" @click="openAMap2(scope.row)">{{ scope.row.isInit == '0' ? '测试描点':'测试调整围点' }}</el-link>-->
                <!-- <el-link type="primary" style="margin:0 5px" :icon="scope.row.claimState == '0' ? 'el-icon-refresh-right' : 'el-icon-loading'" @click="autoClaim(scope.row)">自动认领</el-link> -->
                <el-link v-if="scope.row.sliceType != '0'" type="primary" style="margin:0 5px" @click="openEdit(scope.row)">编辑</el-link>
                <el-link v-if="scope.row.sliceType == '2'" type="danger" style="margin:0 5px" @click="removeRow(scope.row)">删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-box">
          <el-row>
            <el-col :span="24" style="text-align:right">
              <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
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-form ref="form" :key="'sliceAddForm'" v-loading="submitFormLoading" :model="form" label-width="100px" label-position="left" :rules="formRules">
<!--        <el-form-item label="监管所">-->
<!--          <el-cascader v-model="addValue" :options="options" :props="{ expandTrigger: 'hover' }" :show-all-levels="false" @change="handleChange" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="监管所名称" prop="sparentName">-->
<!--          {{ form.sparentName }}-->
<!--        </el-form-item>-->
        <el-form-item label="片区名称" prop="sliceName">
          <el-input v-model="form.sliceName" placeholder="片区名称" />
        </el-form-item>
        <el-form-item label="地址路段" prop="sliceAddr">
          <el-input v-model="form.sliceAddr" placeholder="地址路段" />
        </el-form-item>
        <el-form-item label="监管人员" prop="supervisorId">
          <el-select v-model="form.supervisorId" placeholder="监管人员">
            <el-option v-for="each in userOptions" :key="'supervisorId'+each.primaryKey" :value="each.primaryKey" :label="each.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="片区状态" prop="state">
          <el-radio-group v-model="form.state" size="small">
            <el-radio label="1" border>启用</el-radio>
            <el-radio label="0" border>停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="片区类型" prop="state">
          <el-radio-group v-model="form.sliceType" size="small">
            <el-radio label="1" border>公共片区</el-radio>
            <el-radio label="2" border>详细片区</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="片区说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="片区说明" :autosize="{ minRows: 5, maxRows: 10 }" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-loading="submitFormLoading" type="primary" @click="submitSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import searchHeader from '@/components/searchHeader'
import { getAreaSlicePage, addAreaSlice, modifyAreaSlice, removeAreaSlice, addAutoClaimQueue } from '@/api/areaSlice'
import { getSameDeptUserList } from '@/api/user'
import { getDsmBySparentCode, getInfoBySareaCode, getInfoByUserRegion } from '../../../api/market'
export default {
  components: {
    searchHeader
  },
  data() {
    return {
      user: JSON.parse(sessionStorage.getItem('user')),
      dialogVisible: false,
      showMore: false,
      tableData: [],
      pageParam: {
        curPage: 1,
        pageSize: 10,
        total: 0,
        paramMap: {}
      },
      addValue: [],
      options: [],
      optionsMap: {},
      loading: false,
      searchForm: {
        supervisorName: '',
        sliceName: ''
      },
      form: {
        sliceId: '',
        sliceName: '',
        sliceAddr: '',
        supervisorId: '',
        subSupervisorId: '',
        state: '1',
        remark: '',
        sparentCode: '',
        sparentName: '',
        subUse: '',
        subStartTime: '',
        subEndTime: '',
        sliceType: ''
      },
      dialogTitle: '新建片区',
      formRules: {
        sliceName: [
          { required: true, message: '请输入片区名称', trigger: 'blur' }
        ],
        sliceAddr: [
          { required: true, message: '请输入地址路段', trigger: 'blur' }
        ],
        supervisorId: [
          { required: true, message: '请选择监管人员', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ],
        // sparentName: [
        //   { required: true, message: '请选择监管所', trigger: 'blur' }
        // ]
      },
      submitFormLoading: false,
      userOptions: []
    }
  },
  mounted() {
    this.loadPage()
    // 加载片区待选监督人员
    getSameDeptUserList(this.user.unitId).then(res => {
      if (res.code === 0) {
        this.userOptions = res.data || []
      }
    })

    // const _this = this
    // function setValue(list) {
    //   list.forEach(each => {
    //     each.value = each.sareaCode
    //     each.label = each.sareaName
    //     _this.optionsMap[each.sareaCode] = each
    //     if (each.children) {
    //       setValue(each.children)
    //     }
    //   })
    // }
    // getInfoByUserRegion('1').then(res => {
    //   if (res.code === 0) {
    //     if (res.data) {
    //       setValue(res.data)
    //       this.options = res.data
    //     }
    //   }
    // })
    window.loadPage = this.loadPage
    if (window.top) {
      window.top.loadPage = this.loadPage
    }
  },
  methods: {
    showMoreCriteria() {
      this.showMore = !this.showMore
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    handleChange(value) {
      this.$set(this.form, 'sparentCode', this.optionsMap[value[value.length - 1]].sareaCode)
      this.$set(this.form, 'sparentName', this.optionsMap[value[value.length - 1]].sareaName)
    },
    // 加入自动认领队列
    autoClaim(row) {
      if (row.claimState !== '0') return
      this.$confirm('是否确认将片区加入自动认领队列？').then(_ => {
        row.claimState = '1'
        addAutoClaimQueue(row.sliceId).then(res => {
          if (res.code !== 0) {
            row.claimState = '0'
            this.$message.error(res.msg)
          } else {
            this.$message.success('成功加入自动认领队列')
          }
        })
      }).catch(_ => {})
    },
    // 打开新建窗口
    openCreate() {
      this.dialogTitle = '新建片区'
      this.dialogVisible = true
      this.addValue = []
      this.$nextTick(_ => {
        this.form.sparentCode = ''
        this.form.sparentName = ''
        this.form.sliceName = ''
        this.form.sliceAddr = ''
        this.form.supervisorId = ''
        this.form.subSupervisorId = ''
        this.form.state = ''
        this.form.remark = ''
        this.form.sliceId = null
        this.form.subUse = ''
        this.form.subStartTime = ''
        this.form.subEndTime = ''
      })
    },
    // 打开修改窗口
    openEdit(row) {
      this.dialogTitle = '修改片区'
      this.dialogVisible = true
      this.form.sparentCode = ''
      this.form.sparentName = ''
      const selectOption = []
      // let code = row.sparentCode
      // if (this.$util.isNotEmpty(row.sparentCode)) {
      //   const option = this.optionsMap[row.sparentCode]
      //   if (option) {
      //     this.form.sparentCode = option.sareaCode
      //     this.form.sparentName = option.sareaName
      //   } else {
      //     getInfoBySareaCode({ sareaCode: row.sparentCode }).then(res => {
      //       if (res.code === 0) {
      //         this.optionsMap[row.sparentCode] = res.data
      //         this.form.sparentCode = res.data.sareaCode
      //         this.form.sparentName = res.data.sareaName
      //       }
      //     })
      //   }
      //   // 下拉列表回显
      //   while (this.$util.isNotEmpty(code) && this.optionsMap[code]) {
      //     const curCode = this.optionsMap[code]
      //     const pCode = curCode.sparentCode
      //     if (selectOption.length === 0) {
      //       selectOption[0] = [code]
      //     } else {
      //       const index = selectOption.length - 1
      //       for (let i = index; i > -1; i--) {
      //         selectOption[index + 1] = selectOption[index]
      //       }
      //     }
      //     code = pCode
      //   }
      // }
      this.$nextTick(_ => {
        this.addValue = selectOption
        this.form.sliceName = row.sliceName
        this.form.sliceAddr = row.sliceAddr
        this.form.supervisorId = row.supervisorId
        this.form.subSupervisorId = row.subSupervisorId
        this.form.state = row.state
        this.form.remark = row.remark
        this.form.sliceId = row.sliceId
        this.form.subUse = row.subUse
        this.form.subStartTime = row.subStartTime
        this.form.subEndTime = row.subEndTime
        this.form.sliceType = row.sliceType
      })
    },
    // 删除行
    removeRow(row) {
      this.$confirm('是否确认删除？').then(_ => {
        removeAreaSlice(row.sliceId).then(res => {
          if (res.code === 0) {
            this.loadPage()
            this.$message.success('删除成功')
          }
        })
      }).catch(_ => {})
    },
    // 保存添加/修改
    submitSave() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.submitFormLoading = true
        if (this.$util.isNotEmpty(this.form.sliceId)) {
          // 修改
          modifyAreaSlice(this.form).then(res => {
            this.submitFormLoading = false
            if (res.code === 0) {
              this.dialogVisible = false
              this.loadPage()
              this.$message.success('保存成功')
            }
          })
        } else {
          // 保存
          addAreaSlice(this.form).then(res => {
            this.submitFormLoading = false
            if (res.code === 0) {
              this.dialogVisible = false
              this.loadPage()
              this.$message.success('保存成功')
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    // 加载分页
    loadPage() {
      if (this.loading) return
      this.loading = true
      getAreaSlicePage(this.pageParam).then(res => {
        this.loading = false
        if (res.code === 0) {
          const data = res.data
          const list = []
          let index = (this.pageParam.curPage - 1) * this.pageParam.pageSize
          data.records.forEach(each => {
            each.index = ++index
            each.createTimeStr = this.$util.localDateFormat(each.createTime)
            list.push(each)
          })
          this.tableData = list
          this.pageParam.total = data.total
        }
      })
    },
    // 搜索
    search() {
      if (this.loading) return
      this.pageParam.curPage = 1
      this.pageParam.paramMap = {
        ...this.searchForm
      }
      this.loadPage()
    },
    // 重置搜索
    resetForm() {
      this.searchForm = {
        name: '',
        uscc: '',
        leRepName: '',
        regOrg: '',
        serillrea: ''
      }
    },
    // 当前分页改变
    pageIndexChange(curPage) {
      this.pageParam.curPage = curPage
      this.loadPage()
    },
    // 分页大小改变
    pageSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize
      this.loadPage()
    },
    openAMap(row) {
      const { href } = this.$router.resolve({
        path: `/system/slice/map`,
        query: {
          type: row.isInit === '0' ? 'init' : 'edit',
          id: row.sliceId,
          name: row.sliceName
        }
      })
      window.open(href, '_blank')
    },
    openAMap2(row) {
      const { href } = this.$router.resolve({
        path: `/system/slice/testmap2`,
        query: {
          type: row.isInit === '0' ? 'init' : 'edit',
          id: row.sliceId,
          name: row.sliceName
        }
      })
      window.open(href, '_blank')
    }
  },
  computed: {
    // 是否市监所
    isSjs() {
      return this.user.orgCode.length !== 6
    }
  }
}
</script>

<style lang="scss" scoped>
.main-content{
  background: #fff;
    >div:not(:first-child){
        margin-top:16px;
    }
    .btn-box{
        text-align:right;
    }
    .main-body{
        padding:16px 0;
        .header{
            .header-label{
                font-size: 20PX;
                font-family: Microsoft YaHei, Microsoft YaHei-Bold;
                font-weight: bold;
                color: #243668;
                line-height: 32px;
            }
        }
    }
    .data-state{
      &:before{
        content:'';
        display:inline-block;
        height:8px;
        width:8px;
        border-radius: 50%;
        margin-right:5px;
      }
      &.run:before{
        background:#52C41A;
      }
      &.stop:before{
        background:#D25A5A;
      }
    }
}
/deep/.el-input__inner{
  height: 28px;
}
.search-box{
  background:#fff;
  margin-bottom: 40px;
  padding: 0 10px;
  .search-field{
      display:inline-block;
      width:80%;
      >p{
          margin:0 0 10px 0;
          font-family: Microsoft YaHei, Microsoft YaHei-Bold;
          color: #5e5e7a;
          font-size:16PX;
      }
  }
}
.label-name{
  font-size: $table-content-font-size;
}
.content{
  background: #fff;
  /deep/.el-table .warning-row {
    background: #eaf4fe!important;
  }
}
</style>
