<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="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="5%"
          />
          <el-table-column
            prop="sliceName"
            label="片区名称"
            min-width="10%"
          />
          <el-table-column
            prop="supervisorName"
            label="监管人员"
            min-width="8%"
          />
          <el-table-column
            label="是否顶岗"
            min-width="8%"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.subUse === '1'" class="data-state run">是</span>
              <span v-else class="data-state stop">否</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="subSupervisorName"
            label="顶岗人员"
            min-width="8%"
          />
          <el-table-column
            prop="subStartTime"
            label="开始时间"
            min-width="10%"
          />
          <el-table-column
            prop="subEndTime"
            label="结束时间"
            min-width="10%"
          />
          <el-table-column
            prop="address"
            label="操作"
            min-width="5%"
          >
            <template slot-scope="scope">
              <el-link type="primary" style="margin:0 5px" @click="openEdit(scope.row)">编辑</el-link>
            </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 :props="dicProps" @change="handleChange" filterable :show-all-levels="false" />
        </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="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="subUse">
          <el-radio-group v-model="form.subUse">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.subUse === '1'">
          <el-form-item label="顶岗人员" prop="subSupervisorId">
            <el-select v-model="form.subSupervisorId" 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="subStartTime">
            <el-date-picker
              v-model="form.subStartTime"
              format="yyyy-MM-dd 00:00:00"
              value-format="yyyy-MM-dd 00:00:00"
              :style="{width: '100%'}"
              placeholder="请选择开始时间"
              clearable
            />
          </el-form-item>
          <el-form-item label="结束时间:" prop="subEndTime">
            <el-date-picker
              v-model="form.subEndTime"
              format="yyyy-MM-dd 00:00:00"
              value-format="yyyy-MM-dd 00:00:00"
              :style="{width: '100%'}"
              placeholder="请选择结束时间"
              clearable
            />
          </el-form-item>
        </div>
        <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 } from '../../../api/market'
export default {
  components: {
    searchHeader
  },
  data() {
    return {
      dialogVisible: false,
      showMore: false,
      tableData: [],
      pageParam: {
        curPage: 1,
        pageSize: 10,
        total: 0,
        paramMap: {}
      },
      dicProps: {
        lazy: true,
        label: 'sareaName',
        value: 'sareaCode',
        lazyLoad: async(node, resolve) => {
          console.log(node)
          if (node && node.data && node.data.sareaLevel === '2') {
            const nodes = await this.getDsm(node.data ? node.data.sareaCode : this.user.orgId)
            resolve(nodes.map(item => {
              return {
                ...item,
                leaf: true
              }
            }))
          } else {
            resolve(await this.getDsm(node.data ? node.data.sareaCode : this.user.orgId))
          }
        }
      },
      loading: false,
      searchForm: {
        supervisorName: '',
        sliceName: ''
      },
      form: {
        sliceId: '',
        sliceName: '',
        sliceAddr: '',
        supervisorId: '',
        subSupervisorId: '',
        state: '1',
        remark: '',
        sparentCode: '',
        sparentName: '',
        subUse: '',
        subStartTime: '',
        subEndTime: ''
      },
      dialogTitle: '新建片区',
      formRules: {
        sliceName: [
          { required: true, message: '请输入片区名称', trigger: 'blur' }
        ],
        supervisorId: [
          { required: true, message: '请选择监管人员', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ],
        sparentName: [
          { required: true, message: '请选择监管所', trigger: 'blur' }
        ],
        subUse: [
          { required: true, message: '请选择是否启动顶岗', trigger: 'blur' }
        ],
        subSupervisorId: [
          { required: true, message: '请选择顶岗人员', trigger: 'blur' }
        ],
        subStartTime: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        subEndTime: [
          { required: true, message: '请选择结束时间', trigger: 'blur' }
        ]
      },
      submitFormLoading: false,
      userOptions: [],
      user: JSON.parse(sessionStorage.getItem('user'))
    }
  },
  mounted() {
    this.loadPage()
    // 加载片区待选监督人员
    getSameDeptUserList(this.user.unitId).then(res => {
      if (res.code === 0) {
        this.userOptions = res.data || []
      }
    })
  },
  methods: {
    showMoreCriteria() {
      this.showMore = !this.showMore
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    getDsm(val) {
      return getDsmBySparentCode({ sparentCode: val }).then(res => {
        if (res.code === 0) {
          return res.data
        } else {
          return []
        }
      })
    },
    handleChange(value) {
      console.log(value)
      getInfoBySareaCode({ sareaCode: value[value.length - 1] }).then(res => {
        if (res.code === 0) {
          this.$set(this.form, 'sparentCode', res.data.sareaCode)
          this.$set(this.form, 'sparentName', res.data.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.$nextTick(_ => {
        this.form.sparentCode = ''
        this.form.sparentName = ''
        this.form.sliceName = ''
        this.form.sliceAddr = ''
        this.form.supervisorId = ''
        this.form.subSupervisorId = ''
        this.form.state = '1'
        this.form.remark = ''
        this.form.sliceId = null
        this.form.subUse = '0'
        this.form.subStartTime = ''
        this.form.subEndTime = ''
      })
    },
    // 打开修改窗口
    openEdit(row) {
      this.dialogTitle = '修改片区'
      this.dialogVisible = true
      if (row.sparentCode !== null && row.sparentCode !== undefined && row.sparentCode !== '') {
        getInfoBySareaCode({ sareaCode: row.sparentCode }).then(res => {
          if (res.code === 0) {
            this.form.sparentCode = res.data.sareaCode
            this.form.sparentName = res.data.sareaName
          }
        })
      } else {
        this.form.sparentCode = ''
        this.form.sparentName = ''
      }
      this.$nextTick(_ => {
        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
      })
    },
    // 删除行
    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 {
              this.$message.error(res.msg)
            }
          })
        } 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: `/market/slice/map`,
        query: {
          type: 'init'
        }
      })
      window.open(href, '_blank')
    }
  }
}
</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>
