<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="40"
              @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 :showFooter='false'
              :title="'订阅消息'"
              :isNest="false"
              :visible="diaSubVisible"
              :dialogHeight="1.1"
              :width="60"
              @cancel="diaSubCancel">
      <div style=" position: relative;">
        <div class="div_btn">

          <el-button type="primary"
                     size="mini"
                     @click="syncSubSure">同步默认订阅消息</el-button>

        </div>
        <el-tabs v-model="activeName"
                 class="el-tabs">
          <el-tab-pane label="居民端"
                       name="resi">
            <el-table ref="ref_publictable_resi"
                      v-loading="dataListLoading"
                      :data="resiDataList"
                      border
                      style="width: 100%;">
              <el-table-column prop="tmplId"
                               label="模板ID"
                               header-align="left"
                               :min-width="150"
                               align="left"></el-table-column>
              <el-table-column prop="title"
                               label="标题"
                               header-align="left"
                               :min-width="120"
                               align="left"></el-table-column>

              <el-table-column prop="state"
                               label="状态"
                               header-align="left"
                               :min-width="80">
                <template slot-scope="scope">
                  <span v-if="scope.row.state==='0'"
                        style="color: red">未同步</span>
                  <span v-else-if="scope.row.state==='1'">同步</span>

                </template>
              </el-table-column>

            </el-table>
          </el-tab-pane>
          <el-tab-pane label="工作端"
                       name="gov">
            <el-table ref="ref_publictable_gov"
                      v-loading="dataListLoading"
                      :data="workDataList"
                      border
                      style="width: 100%;">
              <el-table-column prop="tmplId"
                               label="模板ID"
                               header-align="left"
                               :min-width="150"
                               align="left"></el-table-column>
              <el-table-column prop="title"
                               label="标题"
                               header-align="left"
                               :min-width="120"
                               align="left"></el-table-column>

              <el-table-column prop="state"
                               label="状态"
                               header-align="left"
                               :min-width="80">
                <template slot-scope="scope">
                  <span v-if="scope.row.state==='0'"
                        style="color: red">未同步</span>
                  <span v-else-if="scope.row.state==='1'">同步</span>

                </template>
              </el-table-column>
              <!-- <el-table-column prop="stateShow"
                               label="状态"
                               header-align="left"
                               :min-width="100"
                               align="left"></el-table-column> -->

            </el-table>
          </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 { 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',
      dataListLoading: false,
      resiDataList: [],
      workDataList: [],
      resiTempIdList: [],//居民端未同步的模板数组
      workDataList: [],//工作端未同步的模板数组
    }
  },
  components: {
    CTable, CDialog
  },
  activated () {
    this.$nextTick(() => {
      this.$refs.table.doLayout() // 解决表格错位
    })
  },
  mounted () {
    this.tableParams.source = this.env

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

    // eslint-disable-next-line
    this.loadData()
  },
  computed: {
    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.loadSubscribeData(row.customerId) // 解决表格错位
      })
    },

    //加载列表数据
    async loadSubscribeData (customerId) {
      this.dataListLoading = true
      this.selCustomerId = customerId
      // const url = 'https://nei.netease.com/api/apimock-v2/e3b1d0eb88e905f6c7ee559b2d6bb7ad/third/subscribe/getcustomerlist',
      const url = '/third/subscribe/getcustomerlist'
      let params = {
        customerId: customerId,
        workAppId: this.workAppid,
        resiAppId: this.resiAppid,
      }

      const { data, code, msg, internalMsg } = await requestPost(url, params)
      if (code === 0) {
        this.resiDataList = data.resiList
        this.workDataList = data.workList

        this.resiTempIdList = []
        this.workTempIdList = []
        this.resiDataList.forEach(element => {
          if (element.state === '0') {
            this.resiTempIdList.push(element.id)
          }

        })
        this.workDataList.forEach(element => {
          if (element.state === '0') {
            this.workTempIdList.push(element.id)
          }

        })

      } else {
        this.$message.error(msg + "：" + internalMsg)
      }
      this.dataListLoading = false
    },

    //同步客户的订阅消息为默认订阅消息
    async syncSubSure () {
      this.$confirm('确认同步客户的订阅消息为默认订阅消息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.syncSub()
      }).catch(() => {

      })
    },

    async syncSub () {

      this.startLoading()
      // const url = 'https://nei.netease.com/api/apimock-v2/e3b1d0eb88e905f6c7ee559b2d6bb7ad/third/subscribe/init'
      const url = '/third/subscribe/init'

      let params = {
        customerId: this.selCustomerId,
        workAppId: this.workAppid,
        resiAppId: this.resiAppid,
        resiTempIdList: this.resiTempIdList,
        workTempIdList: this.workTempIdList,
      }

      const { data, code, msg, internalMsg } = await requestPost(url, params)
      if (code === 0) {
        this.$message.success('同步成功')
        this.loadSubscribeData(this.selCustomerId)
      } else {
        this.$message.error(msg + "：" + internalMsg)
      }
      this.endLoading()

    },

    // 订阅消息窗口取消
    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">
.aaa {
  height: 100px;
}
.div_btn {
  z-index: 10;
  position: absolute;
  right: 10px;
  top: 5px;
  /* margin: 0 0 20px 0; */
}
</style>
