<template>
  <div class="resi-container">
    <el-card class="resi-card-table">
      <div class="mod-sys__menu">
        <el-table class="table"
                  ref="ref_table"
                  :data="dataList"
                  border
                  :height="tableHeight"
                  v-loading="dataListLoading"
                  :header-cell-style="{background:'#2195FE',color:'#FFFFFF'}"
                  style="width: 100%">
          <el-table-column label="序号"
                           header-align="center"
                           align="center"
                           type="index"
                           width="50"></el-table-column>

          <el-table-column prop="deptName"
                           header-align="center"
                           align="center"
                           label="部门"
                           min-width="100">
          </el-table-column>
          <el-table-column prop="dataName"
                           header-align="center"
                           align="center"
                           label="数据名称"
                           min-width="110">
          </el-table-column>

          <el-table-column label="操作"
                           fixed="right"
                           header-align="center"
                           align="center"
                           width="350">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.stateShow"
                         @change="disableCategory(scope.row,scope.$index)">
              </el-switch>

              <el-button type="text"
                         size="small"
                         class="div-table-button--edit"
                         style="margin-left:20px"
                         @click="editShow(scope.row)">配置</el-button>

            </template>
          </el-table-column>
        </el-table>
        <div>
          <el-pagination @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page.sync="pageNo"
                         :page-sizes="[20, 50, 100, 200]"
                         :page-size="pageSize"
                         layout="sizes, prev, pager, next, total"
                         :total="total">
          </el-pagination>
        </div>

      </div>
    </el-card>

    <!-- 修改弹出框 -->
    <el-dialog :visible.sync="formShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'数据更新配置'"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <div class="div_form">
        <el-form ref="ref_form"
                 :inline="true"
                 :model="formData">

          <el-form-item label="部门"
                        label-width="150px"
                        style="display: block">
           <span>{{selRow.deptName}}</span>
          </el-form-item>
          <el-form-item label="数据名称"
                        label-width="150px"
                        style="display: block">
           <span>{{selRow.dataName}}</span>
          </el-form-item>
          <el-form-item label="适用范围"
                        label-width="150px"
                        style="display: block">
            <el-cascader class="item_width_1"
                         ref="myCascader"
                         v-model="orgIdArray"
                         :key="iscascaderShow"
                         :options="casOptions"
                         :props="optionProps"
                         :show-all-levels="false"
                         @change="handleChangeScope"></el-cascader>

          </el-form-item>

        </el-form>
      </div>

      <div class="div-btn">
        <el-button size="small"
                   @click="diaClose">取 消</el-button>
        <el-button size="small"
                   type="primary"
                   @click="editDiaOK">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { requestPost } from '@/js/dai/request'

import { mapGetters } from 'vuex'
export default {

  data () {
    return {
      customerId: '', // 客户id，父组件传
      customerName: '', // 客户名称，父组件传

      tableParams: {
        customerId: ''
      },
      // tableHeight: 500,
      search: '',
      dataList: [],

      dataListLoading: false,
      total: 0,
      pageSize: 20,
      pageNo: 0,

      casOptions: [],
      iscascaderShow: 0,
      orgIdArray: [],
      selCateObj: {},
      optionProps: {
        multiple: true,
        value: 'agencyId',
        label: 'agencyName',
        orgType: 'orgType',
        children: 'subAgencyList',
        checkStrictly: true
      },

      formShow: false,
      formData: {},

      scopeList: [],
      dataSyncConfigId: '',
      selRow:{}
    }
  },

  computed: {

    tableHeight () {
      const h = this.clientHeight - 220 + this.iframeHeigh
      const _h = this.clientHeight - 220
      return this.$store.state.inIframe ? h : _h
    },

    ...mapGetters(['clientHeight', 'iframeHeight'])
  },
  components: {

  },
  created () {

  },
  async mounted () {
    await this.loadData()
    await this.getOrgList()
  },
  methods: {
    cellStyle ({ row, column, rowIndex, columnIndex }) {
      // 状态列字体颜色
      if (row.state === 'enable' && columnIndex === 1) {
        return 'color: #EA1B29'
      } else if (row.state === 'disable' && columnIndex === 1) {
        return 'color: #0CB618'
      } else {
        return 'color: #1a1a1b'
      }
    },

    diaClose () {
      this.formShow = false
    },

    async getOrgList () {

      // const url = '/gov/org/customeragency/my-subagency-list'
      const url = '/gov/org/customeragency/agencylist'

      let params = {};

      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {

        //组织级联数据
        ++this.iscascaderShow
        this.casOptions = []
        this.orgIdArray.length = []

        if (data) {
          this.casOptions.push(data)

        }

      } else {
        this.$message.error(msg);
      }
    },

    // 加载列表数据
    async loadData () {
      this.dataListLoading = true
      // const url = 'http://yapi.elinkservice.cn/mock/245/epmetuser/dataSyncConfig/list'
      const url = '/epmetuser/dataSyncConfig/list'

      this.tableParams = {
        pageSize: this.pageSize,
        pageNo: this.pageNo
      }

      const { data, code, msg } = await requestPost(url, this.tableParams)
      this.dataListLoading = false
      if (code === 0) {
        this.total = data.total
        this.dataList = data.list
        this.dataList.forEach(element => {

          element.stateShow = element.switchStatus === 'open' ? true : false

        })
      } else {
        // this.$message.error(msg )
      }
    },

    handleChangeScope (value) {
      // console.log('value', value)

      this.orgIdArray = value
      this.scopeList = []
      let selArray = this.$refs["myCascader"].getCheckedNodes()

      // console.log('selArray', selArray)

      selArray.forEach((element, index) => {

        let obj = {
          orgId: element.data.agencyId,
          orgType: element.data.level,
          orgIdPath: element.path.join(':'),

        }
        this.scopeList.push(obj)
      });

      console.log('this.scopeList', this.scopeList)

    },

    // 开启/启用
    disableCategory (row, index) {
      row.switchStatusShow = row.switchStatus === 'open' ? '关闭' : '开启'
      this.$confirm('确认' + row.switchStatusShow, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = '/epmetuser/dataSyncConfig/configSwitch'
        // const url = 'http://yapi.elinkservice.cn/mock/245/epmetuser/dataSyncConfig/configSwitch'
        const param = {
          deptCode: row.deptCode,
          dataSyncConfigId: row.id,

        }
        window.app.ajax.post(url, param,
          (data, rspMsg) => {
            // row.switchStatus = 'open'
            // row.switchStatus = true
            // this.$set(this.dataList, index, row)

            this.$message.success('操作成功')
            this.loadData()
          },
          (rspMsg, data) => {
            this.$message.error(rspMsg)
          })
      }).catch(() => {

      })
    },


    // 编辑 customerId,parentCategoryId,dateform
    editShow (row) {
      this.selRow=row
      this.dataSyncConfigId = row.id

      this.orgIdArray = []
      row.scopeList.forEach(element => {
        if (element.orgIdPath) {
          this.orgIdArray.push(element.orgIdPath.split(':'))
        }

      });

      this.formShow = true

    },

    async editDiaOK () {
      // const url = 'http://yapi.elinkservice.cn/mock/245/epmetuser/dataSyncConfig/scopeSave'
      const url = '/epmetuser/dataSyncConfig/scopeSave'

      let params = {
        dataSyncConfigId: this.dataSyncConfigId,
        scopeList: this.scopeList
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.formShow = false
        this.loadData()
      } else {
        // this.$message.error(msg )
      }
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.pageNo = 1
      this.loadData()
    },
    handleCurrentChange (val) {
      this.pageNo = val
      this.loadData()
    },

    // 取消
    diaCancel () {
      this.$emit('cancleBack')
    },


  }
}
</script>

<style lang="scss" scoped>
.div_form {
  height: 300px;
  padding-top: 50px;
}
.item_width_1 {
  width: 500px;
}
.div-btn {
  margin-top: 50px;
  // margin-bottom:20px;
  display: flex;
  justify-content: center;

  .item_btn {
    font-size: 14px;
    padding: 8px 16px;
    cursor: pointer;
    color: #fff;

    border: 1px dashed #0c81fe;
    border-radius: 6px;
    background-color: #0c81fe;
  }
}
</style>
