<style>
.rule-tree-select .ant-form-item-control {
  line-height: inherit;
}
</style>
<template>
  <div class="ruleSetList">
    <div class="tabBody">
      <a-tabs v-model="tabKey" @change="tabChange">
        <a-tab-pane key="1" tab="模板列表"></a-tab-pane>
        <a-tab-pane key="2" tab="我的模板"> </a-tab-pane>
        <a-button slot="tabBarExtraContent" type="link" @click="toHistory"> 预警历史 </a-button>
      </a-tabs>
    </div>
    <div class="tableBody">
      <!-- <div class="opt" v-if="tabKey == '1'">
        <a-button type="primary" @click="createNewRule">新建空白规则模板</a-button>
        <p class="title">已创建的规则模板</p>
      </div> -->
      <!-- <div class="opts" v-else>
        <a-input-search
          placeholder="请输入规则id"
          style="width: 350px"
          v-model="rulesId"
          enter-button
          @search="onSearch"
        />
      </div> -->
      <div class="table-page-search-wrapper" v-if="tabKey == '2'">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-item label="账户名称">
                <Treeselect :appId.sync="projectId" :multiple="false" ref="treeSelect" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="绑定人">
                <a-input placeholder="请输入绑定的运营" v-model="userName"></a-input>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table">
        <a-table
          size="middle"
          :columns="columns"
          :dataSource="data"
          bordered
          id="outTable"
          :pagination="ipagination"
          :scroll="{ x: scrollX }"
          :loading="loading"
          style="word-break: break-all"
        >
          <span slot="status" slot-scope="text, record">
            <a-spin :spinning="record.spin" size="small">
              <div class="spin-content">
                <a-switch size="default" :checked="text" @change="switchChange(text, record)" />
              </div>
            </a-spin>
            <!-- <a-switch size="default" :checked=text  @change="switchChange(text,record)"/> -->
          </span>
          <span slot="mediaType" slot-scope="text">
            {{ text | handleMediaType }}
          </span>
          <span slot="accountStatus" slot-scope="text">
            <span class="bohui" v-if="text == 1"></span>
            <span class="shenhe" v-if="text == 0"></span>
            {{ text ? '暂停' : '投放中' }}
          </span>
          <span slot="processMethod" slot-scope="text">
            {{ text == 'SEND' ? '仅发送通知' : '发送并关停组' }}
          </span>
          <span slot="options" slot-scope="text, record">
            <a href="javascript:;" @click="editRule(record)">预览模板</a>
            <a-divider type="vertical" />
            <a href="javascript:;" @click="pushRule(record)">推送模板</a>
          </span>
          <span slot="optionsTwo" slot-scope="text, record">
            <a href="javascript:;" @click="editRule(record)">编辑模板</a>
            <a-divider type="vertical" />
            <a-popconfirm :title="`当前删除会解除此账户绑定模板，确定删除吗？`" @confirm="deleteRule(record)">
              <a href="javascript:;">删除模板</a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>
    </div>
    <!-- pushRuleVisible -->
    <a-modal
      v-model="pushRuleVisible"
      title="推送账户选择"
      @ok="handleOk"
      @cancel="cancelPush"
      :confirmLoading="confirmLoading"
      width="60%"
    >
      <a-form layout="inline" class="rule-tree-select">
        <a-form-item
          label="请选择账户"
          :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
          :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
        >
          <Treeselect :appId.sync="accountId" :multiple="false" ref="treeSelect" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import Treeselect from './pushTreeSelect.vue'
import { getAction, postAction, downFile, downFilePost, deleteAction, putAction } from '@/api/manage'
let existColumns = [
  // {
  //     title: '运行/暂停',
  //     dataIndex: 'status',
  //     align: 'center',
  //     width:100,
  //     key: 'status',
  //     scopedSlots: { customRender: 'status' }
  // },
  {
    title: '模板id',
    dataIndex: 'id',
    align: 'center',
    key: 'id',
    scopedSlots: { customRender: 'id' },
  },

  {
    title: '模板名称',
    dataIndex: 'templateName',
    align: 'center',

    key: 'templateName',
    scopedSlots: { customRender: 'templateName' },
  },
  {
    title: '应用媒体',
    dataIndex: 'mediaType',
    align: 'center',
    key: 'mediaType',
    scopedSlots: { customRender: 'mediaType' },
  },

  {
    title: '操作',
    dataIndex: 'options',
    align: 'center',

    key: 'options',
    scopedSlots: { customRender: 'options' },
  },
]

let recordsColumns = [
  {
    title: '运行/暂停',
    dataIndex: 'status',
    align: 'center',
    width: 100,
    key: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '模板名称',
    dataIndex: 'templateName',
    align: 'center',

    key: 'templateName',
    scopedSlots: { customRender: 'templateName' },
  },
  {
    title: '模板Id',
    dataIndex: 'templateId',
    align: 'center',

    key: 'templateId',
    scopedSlots: { customRender: 'templateId' },
  },
  {
    title: '账户',
    dataIndex: 'authName',
    align: 'center',
    key: 'authName',
    scopedSlots: { customRender: 'authName' },
  },
  {
    title: '账户Id',
    dataIndex: 'accountId',
    align: 'center',
    key: 'accountId',
    scopedSlots: { customRender: 'accountId' },
  },
  {
    title: '账户状态',
    dataIndex: 'accountStatus',
    align: 'center',
    key: 'accountStatus',
    scopedSlots: { customRender: 'accountStatus' },
  },
  {
    title: '运营',
    dataIndex: 'userName',
    align: 'center',
    key: 'userName',
    scopedSlots: { customRender: 'userName' },
  },
  {
    title: '操作',
    dataIndex: 'optionsTwo',
    align: 'center',

    key: 'optionsTwo',
    scopedSlots: { customRender: 'optionsTwo' },
  },
]

export default {
  name: 'useRuleList',
  data() {
    return {
      projectId: '',
      userName: '',
      relationCount: 2,
      pushRuleVisible: false,
      confirmLoading: false,
      accountId: '',
      templateId: '',
      tabKey: '1',
      rulesId: undefined,
      data: [],
      columns: [...existColumns],
      scrollX: 0,
      loading: false,
      ipagination: {
        current: 1,
        pageSize: 10,
        //   pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        // showSizeChanger: true,
        // pageSizeOptions: ['10', '30', '50'],
        total: 0,
        onChange: (current, pageSize) => {
          // 切换分页时的回调，
          // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
          this.ipagination.current = current
          this.ipagination.pageSize = pageSize
          let url = ''
          if (this.tabKey == '1') {
            this.columns = [...existColumns]
            url = '/ruleTemplate/list'
          } else {
            this.columns = [...recordsColumns]
            url = '/ruleAccountTemplate/getTemplateApplied'
          }
          this.getTableListHttp(url)
        },
      },
      url: {
        list: '/ruleTemplate/list',
        delete: '/ruleTemplate/delete',
        getRelationAccountById: '/ruleAccountTemplate/getRelationAccountById',
        edit: '',
      },
    }
  },
  components: {
    Treeselect,
  },
  methods: {
    toHistory() {
      this.$router.replace({ path: '/earlyWarningRules/historyWarning' })
    },

    searchQuery() {
      this.ipagination.current = 1
      let url = ''
      if (this.tabKey == '1') {
        this.columns = [...existColumns]
        url = '/ruleTemplate/list'
      } else {
        this.columns = [...recordsColumns]
        url = '/ruleAccountTemplate/getTemplateApplied'
      }
      this.getTableListHttp(url)
    },
    searchReset() {
      this.ipagination.current = 1
      this.projectId = ''
      this.userName = ''
      let url = ''
      if (this.tabKey == '1') {
        this.columns = [...existColumns]
        url = '/ruleTemplate/list'
      } else {
        this.columns = [...recordsColumns]
        url = '/ruleAccountTemplate/getTemplateApplied'
      }
      this.getTableListHttp(url)
    },
    moment,
    onSearch(value) {
      console.log(value)
    },
    tabChange(key) {
      console.log(key)
      this.projectId = ''
      this.userName = ''
      this.ipagination.current = 1
      let url = ''
      if (key == '1') {
        this.columns = [...existColumns]
        url = '/ruleTemplate/list'
      } else {
        this.columns = [...recordsColumns]
        url = '/ruleAccountTemplate/getTemplateApplied'
      }
      this.getTableListHttp(url)
    },
    createNewRule() {
      this.$router.push('/earlyWarningRules/configRules')
    },
    sort(pagination, filters, sorter, { currentDataSource }) {
      this.ipagination.current = pagination.current

      this.ipagination.pageSize = pagination.pageSize
      let url = this.tabKey == '1' ? this.url.existUrl : this.url.resultRecordUrl

      this.getTableListHttp(url)
    },
    editRule(record) {
      console.log(record)
      if (this.tabKey == '1') {
        var data = { id: record.id, edit: false }
      } else {
        var data = { id: record.templateId, edit: true, accountId: record.accountId }
      }

      localStorage.setItem('getRuleDetail', JSON.stringify(data))
      this.$router.push('/earlyWarningRules/ruleModule')
    },
    pushRule(item) {
      // this.confirmLoading
      this.accountId = ''
      this.templateId = item.id
      this.pushRuleVisible = true
    },

    handleOk() {
      if (this.accountId) {
        this.confirmLoading = true
        getAction('/ruleAccountTemplate/checkAccountTemplate', { accountId: this.accountId }).then((res) => {
          console.log(res)
          if (res.success) {
            if (!res.result.isApplication) {
              postAction('/ruleAccountTemplate/pushTemplateToAccount', {
                templateId: this.templateId,
                accountId: this.accountId,
              }).then((r) => {
                if (r.success) {
                  var data = { id: this.templateId, edit: true, accountId: this.accountId }
                  localStorage.setItem('getRuleDetail', JSON.stringify(data))
                  this.$router.push('/earlyWarningRules/ruleModule')
                  this.confirmLoading = false
                  this.accountId = undefined
                } else {
                  this.$message.error(r.message)
                }
              })
            } else {
              // this.accountId = ''
              this.$message.error(`此账户下已绑定模板${res.result.templateName},请重新选择账户`)
              this.confirmLoading = false
            }
          } else {
            // this.accountId = ''
            this.$message.error(res.message)
            this.confirmLoading = false
          }
        })
      } else {
        this.$message.error('请选择需要推送的账户')
      }
    },
    cancelPush() {
      this.accountId = ''
    },
    // recordsRule(record){
    //     console.log(record);

    // },
    showRelativeCount(record) {
      getAction(this.url.getRelationAccountById, {
        id: record.id,
      }).then((res) => {
        console.log(res)
        if (res.success) {
          this.relationCount = res.result.relationCount

          // getAction(this.url.delete,{
          //     id:record.id
          // }).then(res=>{
          //     console.log(res);
          //     if(res.success){
          //         this.getTableListHttp(this.url.list)
          //     }else{
          //         this.$message.error('删除失败')
          //     }
          // })
        }
      })
    },
    deleteRule(record) {
      console.log(record)
      deleteAction('/ruleAccountTemplate/delete', {
        id: record.id,
      }).then((res) => {
        if (res.success) {
          this.getTableListHttp('/ruleAccountTemplate/getTemplateApplied')
          // getAction(this.url.delete,{
          //     id:record.id
          // }).then(res=>{
          //     console.log(res);
          //     if(res.success){
          //         this.getTableListHttp(this.url.list)
          //     }else{
          //         this.$message.error('删除失败')
          //     }
          // })
        }
      })
    },
    switchChange(text, record) {
      console.log(text, record)
      if (record.accountStatus == 0 || (record.accountStatus == 1 && text)) {
        record.spin = true
        let templateStatus = 0
        if (text) {
          templateStatus = 1
        } else {
          templateStatus = 0
        }

        putAction('/ruleAccountTemplate/edit', {
          id: record.id,
          templateStatus,
        }).then((res) => {
          console.log(res)
          record.spin = false
          if (res.success) {
            // this.getTableListHttp()
            if (text) {
              record.status = false
              templateStatus = 1
              this.$message.success('修改成功')
            } else {
              record.status = true
              templateStatus = 0
              this.$message.success('修改成功')
            }
          } else {
            this.$message.error('修改失败')
            // this.getTableListHttp()
          }
        })
      } else {
        this.$message.error('当前账户已关停，预警规则不支持开启！')
      }
    },

    getTableListHttp(url) {
      this.data = []
      this.loading = true
      // let url='/alarm/alarmEventRule/list'
      var params = {}
      if (this.tabKey == '2') {
        params.accountId = this.projectId
        params.userName = this.userName
      }
      getAction(url, {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        ...params,
      }).then((res) => {
        console.log(res)
        this.loading = false
        if (res.success) {
          if (this.tabKey == '1') {
            this.data = res.result.records.map((item) => {
              return {
                ...item,
                status: item.templateStatus == 0 ? true : false,
                spin: false,
              }
            })
          } else {
            this.data = res.result.list.map((item) => {
              return {
                ...item,
                status: item.templateStatus == 0 ? true : false,
                spin: false,
              }
            })
          }

          this.ipagination.total = res.result.total
        }
      })
    },
  },

  mounted() {
    this.getTableListHttp(this.url.list)
  },
  activated() {
    this.getTableListHttp(this.url.list)
  },
  filters: {
    handleMediaType(val) {
      switch (val) {
        case 1:
          return '头条'
          break

        case 2:
          return '快手'
          break

        case 3:
          return '头条'
          break

        case 4:
          return '快手内广'
          break

        default:
          break
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.ruleSetList {
  background: white;
  padding: 20px;
  .tabBody {
    margin-bottom: 5px;
  }
  .tableBody {
    .opt {
      .title {
        margin: 15px 0;
        height: 57px;
        font-size: 16px;
        color: #333;
        line-height: 57px;
        background: #ffffff;
        padding-left: 15px;
        border-radius: 4px 4px 0 0;
        font-weight: 600;
        border-bottom: 1px solid #DADFE3;
      }
    }
    .opts {
      margin-bottom: 15px;
    }

    .shenhe {
      width: 6px;
      height: 6px;
      display: inline-block;
      background: #52C41A;
      border-radius: 50%;
      position: relative;
      top: -2px;
    }
    .bohui {
      width: 6px;
      height: 6px;
      display: inline-block;
      background: #F5222D;
      border-radius: 50%;
      position: relative;
      top: -2px;
    }
  }
}
</style>