<template>
  <div class="registerList">
    <el-card shadow="never"
             class="aui-card--fill">
      <div class="mod-demo__demo}">
        <el-form :inline="true"
                 :model="dataForm"
                 @keyup.enter.native="loadData()">
          <el-form-item>
            <el-input v-model="dataForm.name"
                      placeholder="组织名称">
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button @click="loadData()">查询</el-button>
          </el-form-item>
        </el-form>

        <c-table column-type=""
                 ref="table"
                 :url="tableUrl"
                 :params="tableParams"
                 keyword="RegisterInfo"
                 :operations="operations"
                 :tableHeight="tableHeight"
                 @init="init"
                 @delete="del"
                 @showToken="showToken"
                 @showSubscribe="showSubscribe">
        </c-table>
      </div>
    </el-card>
    <c-dialog :showFooter='false'
              :title="'Token信息'"
              :isNest="false"
              :visible="diaVisible"
              :dialogHeight="1.1"
              :width="60"
              @cancel="diaCancel">
      <el-form :inline="false"
               :model="tokenForm"
               ref="tokenForm"
               :label-width="'120px'">
        <div style="margin-top:20px">
          <el-form-item label="客户名称"
                        prop="customerName">
            <div class="item_width_1">
              <span>{{tokenForm.customerName}}</span>
            </div>
          </el-form-item>
          <el-form-item label="开发token"
                        prop="componentAccessToken">
            <div class="item_width_1">
              <span>{{tokenForm.componentAccessToken}}</span>
            </div>
          </el-form-item>

          <el-form-item label="工作端token"
                        prop="workAuthorizerToken">
            <div class="item_width_1">
              <span>{{tokenForm.workAuthorizerToken}}</span>
            </div>
          </el-form-item>

          <el-form-item label="居民端token"
                        prop="resiAuthorizerToken">
            <div class="item_width_1">
              <span>{{tokenForm.resiAuthorizerToken}}</span>
            </div>
          </el-form-item>

        </div>

      </el-form>
    </c-dialog>

    <c-dialog class="dialogSub"
              :showFooter='false'
              :title="'订阅消息'"
              :isNest="false"
              :visible="diaSubVisible"
              :dialogHeight="1.3"
              :width="80"
              @cancel="diaSubCancel">
      <div ref="ref_sub"
           style=" position: relative;">

        <el-tabs v-model="activeName"
                 class="el-tabs">
          <el-tab-pane label="居民端"
                       name="resi">

            <!-- <div class="div_sub_table">
              <div class="span_sub_title">已添加模板</div>
              <el-button class="btn_sub"
                         type="primary"
                         size="mini"
                         @click="delSubSure()">删除订阅消息</el-button> -->
            <temp-list ref="temp_list_resi_has"
                       :showCustomerTempId="true"
                       :tableType="'sync'"
                       :talbeTitle="'已同步模板'"
                       :btnName="'删除订阅模板'"
                       :activeName="'resi'"
                       @refresh="loadSubscribeData"></temp-list>

            <!-- </div> -->

            <!-- <div class="div_sub_table table2 ">
              <div class="span_sub_title">未添加模板</div>
              <el-button class="btn_sub"
                         type="primary"
                         size="mini"
                         @click="syncSubSure()">同步订阅消息</el-button> -->
            <temp-list ref="temp_list_resi_no"
                       :showCustomerTempId="false"
                       :tableType="'nosync'"
                       :talbeTitle="'未同步模板'"
                       :btnName="'同步订阅模板'"
                       @refresh="loadSubscribeData"
                       :activeName="'resi'"></temp-list>

            <!-- </div> -->
          </el-tab-pane>

          <el-tab-pane label="工作端"
                       name="work">
            <!-- <div class="div_sub_table">
              <div class="span_sub_title">已添加模板</div>
              <el-button class="btn_sub"
                         type="primary"
                         size="mini"
                         @click="delSubSure()">删除订阅消息</el-button> -->
            <temp-list ref="temp_list_work_has"
                       :showCustomerTempId="true"
                       :tableType="'sync'"
                       :talbeTitle="'已同步模板'"
                       :btnName="'删除订阅模板'"
                       @refresh="loadSubscribeData"
                       :activeName="'work'"></temp-list>

            <!-- </div> -->

            <!-- <div class="div_sub_table table2 ">
              <div class="span_sub_title">未添加模板</div>
              <el-button class="btn_sub"
                         type="primary"
                         size="mini"
                         @click="syncSubSure()">同步订阅消息</el-button> -->
            <temp-list ref="temp_list_work_no"
                       :showCustomerTempId="false"
                       :tableType="'nosync'"
                       :talbeTitle="'未同步模板'"
                       :btnName="'同步订阅模板'"
                       @refresh="loadSubscribeData"
                       :activeName="'work'"></temp-list>

            <!-- </div> -->
          </el-tab-pane>
        </el-tabs>
      </div>
    </c-dialog>
  </div>
</template>

<script>
import CDialog from '@c/CDialog'
import CTable from '@c/CTable'
import config from "@/js/dai/config";
import TempList from "./TempList";
import { requestPost } from "@/js/dai/request";
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务

let loading // 加载动画
export default {
  data () {
    return {
      dataForm: {
        name: '' // 组织名称
      },
      workAppid: '',
      resiAppid: '',
      // 列表相关
      tableUrl:
        'https://epmet-cloud.elinkservice.cn/api/third/pacustomer/registerinfo',
      // tableUrl: 'https://nei.netease.com/api/apimock-v2/e3b1d0eb88e905f6c7ee559b2d6bb7ad/third/pacustomer/registerinfo',
      tableParams: {
        source: this.env
      },
      // 列表操作栏的操作项数组
      operations: [
        {
          lable: '初始化', // 按钮显示名称
          size: 'mini',
          style: 'margin: 0 6px;',
          type: 'text',
          slot: '',
          plain: false,
          methodName: 'init', // 回调方法名称
          isShow: (row) => {
            if (
              row.initState === 0 &&
              row.resiAuth === 1 &&
              row.workAuth === 1
            ) {
              return true
            } else {
              return false
            }
          }
        },
        {
          lable: '订阅消息', // 按钮显示名称
          size: 'mini',
          style: 'margin: 0 6px;',
          type: 'text',
          slot: '',
          plain: false,
          methodName: 'showSubscribe', // 回调方法名称
          isShow: (row) => {
            if (
              row.initState === 1
            ) {
              return true
            } else {
              return false
            }
          }
        },
        {
          lable: '删除', // 按钮显示名称
          size: 'mini',
          style: 'margin: 0 6px;',
          type: 'text',
          slot: '',
          plain: false,
          methodName: 'delete', // 回调方法名称
          isShow: (row) => {
            if (this.env !== 'prod') {
              return true
            } else {
              return false
            }
          }
        },
        {
          lable: 'token', // 按钮显示名称
          size: 'mini',
          style: 'margin: 0 6px;',
          type: 'text',
          slot: '',
          plain: false,
          methodName: 'showToken', // 回调方法名称
          isShow: (row) => {
            // if (this.env !== 'prod') {
            return true
            // } else {
            //   return false
            // }
          }
        },

      ],

      // 初始化相关
      initUrl: '/oper/crm/customer/init',

      //token弹出框相关
      diaVisible: false,
      tokenForm: {
        customerId: '',
        customerName: '',
        componentAccessToken: '',
        resiAuthorizerToken: '',
        workAuthorizerToken: ''
      },

      //订阅消息列表相关
      selCustomerId: '',
      diaSubVisible: false,
      activeName: 'resi',

      resiDataList: [],
      workDataList: [],
      resiTempIdList: [],//居民端未同步的模板数组
      workDataList: [],//工作端未同步的模板数组
    }
  },
  components: {
    CTable, CDialog, TempList
  },
  activated () {
    this.$nextTick(() => {
      this.$refs.table.doLayout() // 解决表格错位
    })
  },
  mounted () {

    this.tableParams.source = this.env


    if (this.env === 'test') {//测试
      this.workAppid = config.appId.testWorkAppid
      this.resiAppid = config.appId.testResiAppid
    } else if (this.env === 'prod') {//生产
      this.workAppid = config.appId.prodWorkAppid
      this.resiAppid = config.appId.prodResiAppid
    } else {//开发
      this.workAppid = config.appId.devWorkAppid
      this.resiAppid = config.appId.devResiAppid
    }

    console.log("工作端appId")
    console.log(this.workAppid)
    console.log("居民端appId")
    console.log(this.resiAppid)

    // eslint-disable-next-line
    this.loadData()
  },
  computed: {
    subTabHeight () {
      return this.clientHeight * 0.57 / 2
    },

    tableHeight () {
      return this.clientHeight - 60 - 80 - 80 - 50
    },
    ...mapGetters(['clientHeight', 'env'])
  },
  methods: {
    // 获取列表数据
    loadData () {
      this.$refs.table.loadData()
    },
    // 客户初始化
    init (row) {
      this.startLoading()
      const param = {
        customerId: row.customerId
      }
      window.app.ajax.post(
        this.initUrl,
        param,
        (data, rspMsg) => {
          this.endLoading()
          this.$message.success('初始化成功')
          this.loadData()
          // eslint-disable-next-line
        },
        (rspMsg, data) => {
          this.endLoading()
          this.$message.error(rspMsg)
        }
      )
    },

    //删除客户，开发和体验服显示
    del (row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.startLoading()
        const url = 'https://epmet-cloud.elinkservice.cn/api/third/pacustomer/deletepubliccustomer'
        const param = {
          customerId: row.customerId,
          source: this.env
        }
        window.app.ajax.post(
          url,
          param,
          (data, rspMsg) => {
            this.endLoading()
            this.$message.success('删除成功')
            this.loadData()
            // eslint-disable-next-line
          },
          (rspMsg, data) => {
            this.endLoading()
            this.$message.error(rspMsg)
          }
        )
      })
    },

    //获取token，开发和体验服显示
    showToken (row) {
      this.startLoading()
      const url = 'https://epmet-cloud.elinkservice.cn/api/third/pacustomer/tokenlist'
      const param = {
        customerId: row.customerId
      }
      window.app.ajax.post(
        url,
        param,
        (data, rspMsg) => {
          this.endLoading()
          this.diaVisible = true
          this.$nextTick(() => {
            this.tokenForm = data
          })
          // eslint-disable-next-line
        },
        (rspMsg, data) => {
          this.endLoading()
          this.$message.error(rspMsg)
        }
      )
    },

    // 取消
    diaCancel () {
      this.diaVisible = false
    },

    //订阅消息
    showSubscribe (row) {
      this.diaSubVisible = true
      this.resiDataList = []
      this.workDataList = []
      this.$nextTick(() => {
        this.selCustomerId = row.customerId

        this.loadSubscribeData()

      })
    },


    //加载列表数据
    async loadSubscribeData () {
      this.$refs.temp_list_resi_has.setTableLoading()
      this.$refs.temp_list_resi_no.setTableLoading()
      this.$refs.temp_list_work_has.setTableLoading()
      this.$refs.temp_list_work_no.setTableLoading()
      // const url = 'https://nei.netease.com/api/apimock-v2/e3b1d0eb88e905f6c7ee559b2d6bb7ad/third/subscribe/getcustomerlist'
      const url = 'https://epmet-cloud.elinkservice.cn/api/third/subscribe/getcustomerlist'
      let params = {
        customerId: this.selCustomerId,
        resiAppId: this.resiAppid,
        workAppId: this.workAppid
        // sync: sync
      }

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

        let resiList = []
        let resiList_sync = []
        let resiList_sync_no = []

        let workList = []
        let workList_sync = []
        let workList_sync_no = []


        data.resiList.forEach(element => {
          if (element.state === '0') {
            resiList_sync_no.push(element)
          } else {
            resiList_sync.push(element)
          }
        })

        data.workList.forEach(element => {
          if (element.state === '0') {
            workList_sync_no.push(element)
          } else {
            workList_sync.push(element)
          }
        })
        this.$refs.temp_list_resi_has.setTableData(resiList_sync, this.selCustomerId, this.resiAppid, this.workAppid)
        this.$refs.temp_list_resi_no.setTableData(resiList_sync_no, this.selCustomerId, this.resiAppid, this.workAppid)
        this.$refs.temp_list_work_has.setTableData(workList_sync, this.selCustomerId, this.resiAppid, this.workAppid)
        this.$refs.temp_list_work_no.setTableData(workList_sync_no, this.selCustomerId, this.resiAppid, this.workAppid)


      } else {
        this.$message.error(msg + "：" + internalMsg)
      }
      this.$refs.temp_list_resi_has.setTableLoading()
      this.$refs.temp_list_resi_no.setTableLoading()
      this.$refs.temp_list_work_has.setTableLoading()
      this.$refs.temp_list_work_no.setTableLoading()
    },

    // 订阅消息窗口取消
    diaSubCancel () {
      this.diaSubVisible = false
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  }
}
</script>
<style lang="css" >
.dialogSub .el-dialog__body {
  padding: 0 20px 10px 20px;
}
.div_btn {
  z-index: 10;
  position: absolute;
  right: 10px;
  top: 5px;
  /* margin: 0 0 20px 0; */
}
.el-tabs {
  /* height: 2000px; */
}
.div_sub_table {
  /* margin: 10px 10px; */
  position: relative;
}
.table2 {
  margin-top: 20px;
}
.span_sub_title {
  /* height: 30px;
  line-height: 30px; */
  font-size: 16px;
  padding: 5px 0 10px 0;
}
.btn_sub {
  position: absolute;
  right: 10px;
  top: 0px;
}
</style>
