<template>
  <div class="pageIndex">
    <div style="border:1px solid #ccc;border-radius: 10px;padding:20px">
      <el-descriptions class="margin-top" title="二级渠道信息" :column="3">
        <template slot="extra">
          <el-button type="primary" size="small" @click="editShow(2)">编辑</el-button>
          <el-button type="primary" @click="recordClick" size="small">历史记录</el-button>
        </template>
        <el-descriptions-item label="渠道名称">
          {{ content.channelName }}
        </el-descriptions-item>
        <el-descriptions-item label="渠道编码">
          {{ content.channelCodeOne }}{{ content.channelCodeTwo }}
        </el-descriptions-item>
        <el-descriptions-item label="生效日期">
          {{ content.onlineTime }}
        </el-descriptions-item>
        <el-descriptions-item label="合作方">
          {{ content.channelPartner }}
        </el-descriptions-item>
        <el-descriptions-item label="合作方联系人">
          {{ content.partnerContacts }}
        </el-descriptions-item>
        <el-descriptions-item label="合作方联系人电话">
          {{ content.partnerPhone }}
        </el-descriptions-item>
        <el-descriptions-item label="联通负责人">
          {{ content.unicomContacts }}
        </el-descriptions-item>
        <el-descriptions-item label="联通负责人联系方式">
          {{ content.unicomPhone }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div style="margin: 20px 0;">
      <el-form :inline="true" :model="searchForm" ref="searchForm" size="small">
        <el-form-item label="渠道名称">
          <el-input v-model="searchForm.channelName" name="searchForm.channelName" placeholder="策略名称" />
        </el-form-item>
        <el-form-item label="合作方">
          <el-input v-model="searchForm.channelPartner" placeholder="合作方" />
        </el-form-item>
        <el-form-item label="选择策略(新)">
          <el-select v-model="searchForm.strategyId" clearable filterable>
            <el-option v-for="item in strategyList" :key="item.id" :label="item.strategyName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.channelStatus" clearable>
            <el-option label="生效中" :value="1"></el-option>
            <el-option label="未生效" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="策略状态">
          <el-select v-model="searchForm.onOffStatus" clearable>
            <el-option label="新版本" :value="1"></el-option>
            <el-option label="旧版本" :value="2"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item>
          <el-button type="primary" @click="init()">搜索</el-button>
          <el-button type="danger" @click="pushdata = true">同步科创</el-button>
          <el-button @click="reset('searchForm')">刷新</el-button>
          <el-button type="warning" @click="download()">导出</el-button>
          <el-button type="primary" plain icon="el-icon-plus" @click="channelShow2 = true">新增三级渠道</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <!-- <vxe-toolbar>
        <template #buttons>
          <vxe-button icon="fa fa-plus" >新增二级渠道</vxe-button>
          <vxe-button @click="init()">刷新</vxe-button>
          <vxe-button v-if="checkData.length>0" @click="modifyClick">批量修改</vxe-button>
        </template>
      </vxe-toolbar> -->
      <div class="infoList">
        已选择{{ checkData.length }}项
        <el-button v-if="checkData.length > 0" style="margin-left: 20px" type="primary" icon="el-icon-edit" size="mini"
          @click="drawerClick">批量修改</el-button>
        <el-button v-if="syncList.length > 0" style="margin-left: 20px" type="primary" icon="el-icon-edit" size="mini"
          @click="syncInfos">批量同步渠道信息</el-button>
      </div>
      <el-table max-height="700" border @selection-change="selectionChnage" highlight-current-row :data="tableData"
        :header-cell-style="{ 'background-color': '#E4E7ED', color: '#000' }" style="width: 100%;">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="channelName" label="渠道名称" />
        <el-table-column prop="channelKey" label="渠道Key" />
        <el-table-column prop="standardFullCode" label="标准渠道编码" />
        <el-table-column prop="fullCode" label="完整渠道编码" />
        <el-table-column label="渠道类别">
          <template slot-scope="scope">
            <span v-if="scope.row.channelType == 1">集团渠道</span>
            <span v-else-if="scope.row.channelType == 2">省分线下渠道</span>
            <span v-else-if="scope.row.channelType == 3">省分线上渠道</span>
            <span v-else-if="scope.row.channelType == 4">互联网渠道</span>
            <span v-else-if="scope.row.channelType == 5">自有线上渠道</span>
            <span v-else-if="scope.row.channelType == 6">社会代理和其他渠道</span>
            <span v-else> <span style="color:red">(旧)</span> {{ scope.row.channelType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="渠道形态">
          <template slot-scope="scope">
            <span v-if="scope.row.channelPattern == 1">线上H5/小程序渠道</span>
            <span v-else-if="scope.row.channelPattern == 2">接口渠道</span>
            <span v-else-if="scope.row.channelPattern == 3">反向通知渠道</span>
          </template>
        </el-table-column>
        <el-table-column label="渠道版本">
          <template slot-scope="scope">
            <span v-if="scope.row.onOffStatus == 1" style="color:#67C23A">新版本</span>
            <span v-else style="color:#F56C6C">旧版本</span>
          </template>
        </el-table-column>
        <el-table-column label="渠道同步" width="150">
          <template slot-scope="scope">
            <div>
              流量中台: <span v-if="scope.row.liuliangSyncState == 1" style="color:#67C23A">成功</span><span
                v-else-if="scope.row.liuliangSyncState == 0" style="color:#F56C6C">失败</span><span style="color:#909399"
                v-else>未同步</span>
            </div>
            <div>
              权益中台: <span v-if="scope.row.quanyiSyncState == 1" style="color:#67C23A">成功</span><span
                v-else-if="scope.row.quanyiSyncState == 0" style="color:#F56C6C">失败</span><span style="color:#909399"
                v-else>未同步</span>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="channelPartner" label="合作方" /> -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.channelStatus == 1" style="color:#67C23A">生效中</span>
            <span v-else-if="scope.row.channelStatus == 0" style="color:#F56C6C">未生效</span>
          </template>
        </el-table-column>
        <el-table-column prop="onlineTime" label="生效时间" />
        <el-table-column fixed="right" label="操作" width="420">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editShow(3, scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="productEdit(scope.row)">编辑策略</el-button>
            <el-button type="text" size="small" @click="checkpushdata(scope.row)">查询同步</el-button>
            <el-button type="text" size="small" @click="copy(scope.row)">复制链接</el-button>
            <el-button type="text" size="small" @click="giveShort(scope.row)">短连接</el-button>
            <el-button type="text" size="small" @click="ewm(scope.row)">二维码</el-button>
            <el-button type="text" size="small" @click="syncInfo(scope.row)">同步渠道信息</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination style="float: right" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchForm.pageNum" :page-sizes="[10, 20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper" :total="searchForm.totalResult"
          :page-size="searchForm.pageSize">
        </el-pagination>
      </div>
      <!-- <vxe-pager :loading="loading" :current-page="searchForm.pageNum" :page-size="searchForm.pageSize" :total="searchForm.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange" /> -->
      <el-dialog title="二维码下载" :visible.sync="dialogVisible" width="350px">
        <div style="text-align: center">
          <div id="qrcode"></div>
          <div style="height: 25px;line-height: 25px;margin-top: 30px">鼠标右键图片另存为</div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <!-- 历史记录 -->
      <vxe-modal v-model="value5" width="60%" title="历史记录">
        <template #default>
          <vxe-toolbar>
            <template #buttons>
              <vxe-input v-model="channelogParam.notes" type="search" clearable placeholder="搜索操作记录"></vxe-input>
              <vxe-input v-model="channelogParam.userName" type="search" clearable placeholder="搜索操作人"></vxe-input>
              <vxe-button @click="recordClick" content="搜索"></vxe-button>
            </template>
          </vxe-toolbar>
          <vxe-table auto-resize height="600" :data="channelog">
            <vxe-table-column field="createTime" title="时间"></vxe-table-column>
            <vxe-table-column field="notes" title="操作记录">
              <template slot-scope="props">
                <div v-html="props.row.notes"></div>
              </template>
            </vxe-table-column>
            <vxe-table-column field="userName" title="操作人"></vxe-table-column>
          </vxe-table>
          <vxe-pager :loading="loading" :current-page="channelogParam.pageNum" :page-size="channelogParam.pageSize"
            :total="channelogParam.totalResult"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
            @page-change="handlePageChangeChannelog" />
        </template>
      </vxe-modal>

      <vxe-modal title="同步" v-model="pushdata" width="600">
        <template #default>
          <el-form ref="form" label-width="80px">
            <el-form-item label="选择时间">
              <el-date-picker v-model="pushdataDate" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">立即同步</el-button>
              <el-button @click="pushdata = false">取消</el-button>
            </el-form-item>
          </el-form>
        </template>
      </vxe-modal>
    </div>
    <el-dialog title="批量修改" :visible.sync="modifyShow" width="50%">
      <el-form style="width:70%" label-width="100px">
        <el-form-item label="基础策略">
          <el-select v-model="baseStrategy" placeholder="请选择" clearable filterable>
            <el-option v-for="item in strategyList" :key="item.id" :label="item.strategyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="高级策略">
          <el-select v-model="seniorStrategy" placeholder="请选择" clearable filterable>
            <el-option v-for="item in seniorStrategyList" :label="item.name" :key="item.id" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <div style="color:#F56C6C">使用批量修改前,请先确保所有渠道均为新版本!</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyShow = false">取 消</el-button>
        <el-button type="primary" @click="sure()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑二级渠道弹窗 -->
    <el-dialog title="编辑二级渠道" :visible.sync="channelShow" width="55%" top="5vh" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="form" v-if="channelShow" :model="form" :rules="rules" label-width="120px" style="width:60%">
        <el-form-item label="渠道名称" prop="channelName" required>
          <el-input placeholder="请输入内容" v-model="form.channelName"></el-input>
        </el-form-item>
        <el-form-item label="一级编码" prop="channelCodeOne" required>
          <el-input placeholder="请输入内容" v-model="form.channelCodeOne"></el-input>
        </el-form-item>
        <el-form-item label="上线时间" prop="onlineTime" required>
          <el-date-picker type="datetime" placeholder="选择日期" v-model="form.onlineTime" value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合作方">
          <el-input placeholder="请输入内容" v-model="form.channelPartner"></el-input>
        </el-form-item>
        <el-form-item label="合作方联系人">
          <el-input placeholder="请输入内容" v-model="form.partnerContacts"></el-input>
        </el-form-item>
        <el-form-item label="合作方联系方式">
          <el-input placeholder="请输入内容" v-model="form.partnerPhone"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="unicomContacts" required>
          <el-input placeholder="请输入内容" v-model="form.unicomContacts"></el-input>
        </el-form-item>
        <el-form-item label="负责人电话" prop="unicomPhone" required>
          <el-input placeholder="请输入内容" v-model="form.unicomPhone"></el-input>
        </el-form-item>
        <el-form-item label="外部接口">
          <el-input placeholder="请输入内容" v-model="form.apiUrl"></el-input>
        </el-form-item>
        <el-form-item label="生效状态">
          <el-radio v-model="form.channelStatus" :label="0">失效</el-radio>
          <el-radio v-model="form.channelStatus" :label="1">生效</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="channelShow = false">取 消</el-button>
        <el-button type="primary" @click="editChannel(2)">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增三级渠道弹窗 -->
    <el-dialog :title="isEdit == 1 ? '编辑三级渠道' : '新建三级渠道'" :visible.sync="channelShow2" width="55%" top="5vh"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="form2" v-if="channelShow2" :model="form2" :rules="rules2" label-width="120px" style="width:60%">
        <el-form-item label="渠道名称" prop="channelName" required>
          <el-input placeholder="请输入内容" v-model="form2.channelName"></el-input>
        </el-form-item>
        <el-form-item label="渠道类别" prop="channelType" required>
          <el-select :disabled="standardFullCode != null && standardFullCode != ''" v-model="form2.channelType" clearable
            placeholder="渠道类别">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <span v-if="isEdit == 1">
            <span v-if="isNaN(form2.channelType)" style="color:red;margin-left:15px">当前为旧类型,请重新选择</span>
          </span>
        </el-form-item>
        <el-form-item label="渠道形态" prop="channelPattern" required>
          <el-select :disabled="standardFullCode != null && standardFullCode != ''" v-model="form2.channelPattern"
            placeholder="渠道类别">
            <el-option v-for="item in  patternList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <!-- <el-input placeholder="请输入内容" v-model="form2.channelName"></el-input> -->
        </el-form-item>
        <el-form-item label="二级渠道编码">
          <el-input placeholder="请输入内容" disabled :value="content.channelCodeOne + content.channelCodeTwo"></el-input>
        </el-form-item>
        <el-form-item label="完整渠道编码" v-if="standardFullCode != '' && standardFullCode != null">
          <el-input disabled :value="standardFullCode"></el-input>
        </el-form-item>
        <el-form-item label="上线时间" prop="onlineTime" required>
          <el-date-picker type="datetime" placeholder="选择日期" v-model="form2.onlineTime" value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="基本策略" prop="strategyId" required>
          <el-select v-model="form2.strategyId" filterable clearable placeholder="请选择策略" :loading="loading">
            <el-option v-for="item in strategyList" :key="item.id" :label="item.strategyName"
              :value="item.id"></el-option>
          </el-select>
          <span style="margin-left: 20px">
            <vxe-button @click="getStrategyList" icon="el-icon-refresh" size="mini" content="刷新"></vxe-button>
          </span>
          <span style="margin-left: 20px">
            <vxe-button @click="toAdd" icon="el-icon-plus" size="mini" content="新建"></vxe-button>
          </span>
          <span v-if="form2.strategyId" style="margin-left: 20px">
            <vxe-button @click="editStrate(form2.strategyId)" icon="el-icon-edit" size="mini" content="编辑"></vxe-button>
          </span>
        </el-form-item>
        <el-form-item label="高级策略">
          <el-select filterable clearable placeholder="高级策略" v-model="form2.adStrategyId">
            <el-option v-for="item in seniorStrategyList" :label="item.name" :key="item.id" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生效状态">
          <el-radio v-model="form2.channelStatus" :label="0">失效</el-radio>
          <el-radio v-model="form2.channelStatus" :label="1">生效</el-radio>
        </el-form-item>
        <el-form-item label="流量fes">
          <el-input placeholder="请输入内容" v-model="form2.fes"></el-input>
          <div style="color: red;">提示：原流量平台不支持订购记录查询</div>
        </el-form-item>
        <el-form-item label="流量sou">
          <el-input placeholder="请输入内容" v-model="form2.sou"></el-input>
          <div style="color: red;">提示：原流量平台不支持订购记录查询</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAdd">取 消</el-button>
        <el-button type="primary" :disabled="isEdit == 1 && form2.channelPattern != '1'"
          @click="isEdit == 0 ? addChannel() : editChannel(3)">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  post,
  get
} from '@/api/common'
import QRCode from 'qrcodejs2'
import axios from "axios";
import {
  getToken
} from "../../utils/auth";
const XEUtils = require("xe-utils");

export default {
  name: 'SchemeEdit',
  data () {
    return {
      searchForm: {
        onOffStatus: null,
        strategyId: null,
        channelStatus: null,
        channelName: '',
        channelPartner: '',
        parentId: 0,
        pageNum: 1,
        pageSize: 10,
        totalResult: 0
      },
      loading: false,
      tableData: [],
      content: {},
      dialogVisible: false,
      value5: false,
      pushdata: false,
      pushdataDate: '',
      channelog: [],
      channelogParam: {
        channelId: this.$route.query.id,
        type: 2,
        pageNum: 1,
        pageSize: 10,
        totalResult: 0
      },
      strategyList: [],
      checkData: [],
      modifyShow: false,
      baseStrategy: "",
      // baseStrategyList: [],
      seniorStrategy: "",
      seniorStrategyList: [],
      infoList: [],
      channelShow: false,
      channelShow2: false,
      form: {
        channelTag: "",//二级渠道
        channelName: "",//渠道名称
        channelCodeOne: "", //一级编码
        onlineTime: "",//上线时间
        channelPartner: "",//合作方
        partnerContacts: "",//合作方联系人
        partnerPhone: "",//合作方联系方式
        unicomContacts: "",//联通负责人
        unicomPhone: "",//联通负责人电话
        apiUrl: "",//外部接口
        channelStatus: "",
      },
      rules: {
        channelName: [{ required: true, message: '请输入渠道名称', trigger: 'blur' }],
        channelCodeOne: [{ required: true, message: '一级渠道编码不能为空', trigger: 'blur' }],
        onlineTime: [{ required: true, message: '请选择时间', trigger: 'change' }],
        channelPartner: [{ required: true, message: '合作方不能为空', trigger: 'blur' }],
        partnerContacts: [{ required: true, message: '合作方联系人不能为空', trigger: 'blur' }],
        partnerPhone: [{ required: true, message: '合作方联系方式不能为空', trigger: 'blur' }],
        unicomContacts: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
        unicomPhone: [{ required: true, message: '负责人联系方式不能为空', trigger: 'blur' }],
      },
      oldForm: {},
      channelId: "",
      form2: {
        channelTag: 3,
        parentId: "",  //二级渠道id
        channelStatus: 1, //三级渠道生效状态
        adStrategyId: "", //高级策略
        strategyId: "", //基本策略
        onlineTime: "", //上线时间
        channelName: "", //渠道名称
        channelType: null, //渠道类别
        channelPattern: null, //渠道类别
        channelCodeOne: "", //一级渠道编码
        channelCodeTwo: "", //二级渠道编码
        channelCodeThree: "", //三级渠道编码
        onOffStatus: 1,
        fes: "",
        sou: ""
      },
      rules2: {
        channelName: [{ required: true, message: '请输入渠道名称', trigger: 'blur' }],
        channelType: [{ required: true, message: '渠道类别不能为空', trigger: 'change' }],
        channelPattern: [{ required: true, message: '渠道形态不能为空', trigger: 'change' }],
        onlineTime: [{ required: true, message: '请选择时间', trigger: 'change' }],
        strategyId: [{ required: true, message: '请选择基础策略', trigger: 'change' }],
      },
      // 渠道类别
      typeList: [{ value: "1", label: '集团渠道' },
      { value: "2", label: '省分线下渠道' },
      { value: "3", label: '省分线上渠道' },
      { value: "4", label: '互联网渠道' },
      { value: "5", label: '自有线上渠道' },
      { value: "6", label: '社会代理和其他渠道' },
      ],
      // 渠道形态
      patternList: [
        { value: "1", label: '线上H5/小程序渠道' },
        { value: "2", label: '接口渠道' },
        { value: "3", label: '反向通知渠道' },
      ],
      isEdit: 0,
      updateForm: {},
      syncList: [],
      standardFullCode: "" //完整渠道编码
    }
  },
  created () {
    document.title = '二级渠道详情'
    this.searchForm.parentId = this.$route.query.id
    this.channelId = this.$route.query.id
    this.getyChannelDetail()
  },
  mounted () {
    this.getStrategyList()
    this.getSeniorStrategy()
    // this.getBaseStrategy()
  },
  methods: {
    syncInfos () {
      if (this.syncList.length > 0) {
        let str = ''
        this.syncList.forEach(val => {
          str = val.channelKey + ',' + str
        })
        post('/channelInfo/pushdata/batch', { ids: str }).then(res => {
          // console.log()
          if (res.code == 10000) {
            this.$message.success('调用同步成功')
            this.syncList = []
            this.init()
          }
        })
      }
    },
    syncInfo (row) {
      post('/channelInfo/pushdata/batch', { ids: row.channelKey }).then(res => {
        // console.log()
        if (res.code == 10000) {
          this.$message.success('调用同步成功')
          this.init()
        }
      })
    },
    // 刷新策略
    toAdd () {
      let routeUrl = this.$router.resolve({
        path: '/strategy/add'
      })
      window.open(routeUrl.href, '_blank')
    },
    // 编辑策略
    editStrate (e) {
      const routeUrl = this.$router.resolve({
        path: '/strategy/add',
        query: {
          id: e,
          editId: 1
        }
      })
      window.open(routeUrl.href, '_blank')
    },
    // 获取二级渠道信息
    getyChannelDetail () {
      get('/channelInfo/detail', {
        id: this.channelId
      }).then(res => {
        this.content = res.data
        this.form2.parentId = res.data.id
        this.form2.channelCodeTwo = res.data.channelCodeTwo
        this.form2.channelCodeOne = res.data.channelCodeOne
        this.init()
      })
    },
    editShow (num, row) {
      if (num == 2) {
        for (let key in this.content) {
          this.form[key] = this.content[key]
        }
        if (this.content.channelCodeOne == '0' || this.content.channelCodeOne == null || this.content.channelCodeOne == '') {
          this.form.channelCodeOne = '6602'
        }
        this.channelShow = true
        this.oldForm = JSON.parse(JSON.stringify(this.content))
      } else {
        this.isEdit = 1
        this.channelShow2 = true
        for (let i in this.form2) {
          this.form2[i] = row[i]
        }
        this.standardFullCode = row.standardFullCode
        this.updateForm = row
        this.oldForm = JSON.parse(JSON.stringify(row))
      }
    },
    closeAdd () {
      this.channelShow2 = false
      for (let i in this.form2) {
        this.form2[i] = ""
      }
      this.form2.parentId = this.channelId
      this.form2.channelCodeTwo = this.content.channelCodeTwo
      this.form2.channelCodeOne = this.content.channelCodeOne
      this.form2.onOffStatus = 1
      this.form2.channelTag = 3
      this.form2.channelStatus = 1
      this.isEdit = 0
      this.standardFullCode = ''
    },
    // 新增三级渠道
    addChannel () {
      this.form2.channelCodeThree = `${this.form2.channelType}${this.form2.channelPattern}`
      this.$refs['form2'].validate((valid) => {
        if (valid) {
          post('/channelInfo/create', this.form2).then(res => {
            if (res.code == 10000) {
              this.$message.success('创建成功!')
              this.closeAdd()
              this.reset()
            }
            // console.log(res)
          })
        }
      })
    },
    // 修改二级渠道
    editChannel (num) {
      if (num == 2) {
        for (let key in this.form) {
          this.content[key] = this.form[key]
        }
        var array1 = this.oldForm;
        var array2 = this.content;
        let text = '渠道：' + this.content.channelName
        XEUtils.objectEach(array2, (item, key) => {
          if (item != array1[key]) {
            text += `\n${key}:${array1[key]} 改为 ${item}`;
          }
        })
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.content.channelTag = 3
            post('/channelInfo/update/' + this.channelId, this.content).then(res => {
              this.$message.success('修改成功!')
              this.channelShow = false
              this.getyChannelDetail()
              post('/channelInfo/createChannlelog', {
                'type': 2,
                'notes': text,
                'channelId': this.channelId
              })
            })

          }
        })
      } else {
        for (let key in this.form2) {
          this.updateForm[key] = this.form2[key]
          if (key == 'channelType') {
            if (isNaN(this.updateForm[key])) {
              this.updateForm[key] = this.typeList.find(val => {

                return val.label == this.form2[key]
              }).value

            }

          }

        }
        var array1 = this.oldForm;
        var array2 = this.updateForm;
        let text = '渠道：' + this.updateForm.channelName
        XEUtils.objectEach(array2, (item, key) => {
          if (item != array1[key]) {
            text += `\n${key}:${array1[key]} 改为 ${item}`;
          }
        })

        this.$refs['form2'].validate((valid) => {
          if (valid) {
            this.updateForm.channelCodeTwo = this.content.channelCodeTwo
            this.updateForm.channelCodeOne = this.content.channelCodeOne

            this.updateForm.channelCodeThree = `${this.form2.channelType}${this.form2.channelPattern}`
            this.updateForm.onOffStatus = 1
            this.updateForm.channelTag = 3
            console.log(this.updateForm)
            post('/channelInfo/update/' + this.oldForm.id, this.updateForm).then(res => {
              this.$message.success('修改成功!')
              this.channelShow2 = false
              this.getyChannelDetail()
              post('/channelInfo/createChannlelog', {
                'type': 2,
                'notes': text,
                'channelId': this.channelId
              })
            })

          }
        })
      }


    },
    handleSizeChange (val) {
      this.searchForm.pageSize = val
      this.searchForm.pageNum = 1
      this.init()
    },
    handleCurrentChange (val) {
      this.searchForm.pageNum = val
      this.init()
    },
    selectionChnage (e) {
      if (e) {
        this.syncList = e
        this.checkData = e;
      }
    },
    // 打开修改记录
    recordClick () {
      get('/channelInfo/channelogpage', this.channelogParam).then(res => {
        this.channelog = res.data.list
        this.channelogParam.totalResult = res.data.total
        this.value5 = true
      })
    },
    drawerClick () {
      if (this.checkData.length > 10) {
        this.$confirm('批量修改不能超过10条数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } else {
        this.infoList = []
        this.checkData.forEach(async (val, index) => {
          await get('/channelInfo/detail', { id: val.id }).then(res => {
            this.infoList.push(res.data)
            if (index == 0) {
              this.baseStrategy = this.infoList[index].strategyId
              this.seniorStrategy = this.infoList[index].adStrategyId
            }
          })

        })
        this.modifyShow = true
      }

    },
    // 确认批量修改
    sure () {
      this.infoList.forEach((val, index) => {
        let oldobj = Object.assign({}, val)
        val.strategyId = this.baseStrategy
        val.adStrategyId = this.seniorStrategy
        post('/channelInfo/update/' + val.id, val).then(res => {
          this.addRecord(oldobj)
          if (this.infoList.length == (index + 1)) {
            this.$message.success('修改成功!')
            this.modifyShow = false
            this.getStrategyList()
          }
        })

      })
    },
    // 新增修改策略记录
    addRecord (item) {
      let { strategyId, adStrategyId } = item
      let oldObj = { strategyId, adStrategyId }
      let newObj = {
        strategyId: this.baseStrategy,
        adStrategyId: this.seniorStrategy
      }
      let text = "渠道：" + item.channelName;
      XEUtils.objectEach(newObj, (i, k) => {
        if (i != oldObj[k]) {
          text += `\n${k}:${oldObj[k]} 改为 ${i ? i : "空"}`;
        }
      });
      let params = {
        notes: text,
        channelId: item.parentId,
        type: 2,
      };
      post("/channelInfo/createChannlelog", params);
    },

    // 获取高级策略列表
    getSeniorStrategy () {
      get('/strategysenior/list', { pageNum: 1, pageSize: 99999 }).then(res => {
        this.seniorStrategyList = res.data.list
      })
    },
    productEdit (item) {
      if (item.onOffStatus == 1) {
        const routeUrl = this.$router.resolve({
          path: "/strategy/add",
          query: { id: item.strategyId, editId: 1 },
        });
        window.open(routeUrl.href, "_blank");
      } else {
        this.$message.warning('请将当前渠道绑定新策略')
      }

    },
    getStrategyList () {
      get("/strategytemplate/list", { pageSize: 99999, pageNum: 1 }).then((res) => {
        this.strategyList = res.data.list
      });
    },
    formatterWotv ({
      cellValue
    }) {
      return cellValue !== '1' ? '关闭' : '开启'
    },
    //导出
    download () {
      let formData = new FormData();
      formData.append("channelName", "");
      formData.append("channelStatus", 1);
      formData.append("parentId", this.searchForm.parentId);
      let loading = this.$loading({
        lock: true,
        text: "下载量较大,请耐心等待",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      axios({
        method: "post",
        url: process.env.VUE_APP_BASE_API + "/channelInfo/download",
        data: formData,
        responseType: "blob",
        headers: {
          "Content-Type": "multipart/form-data",
          token: getToken(),
        },
      }).then((res) => {
        if (res.data) {
          loading.close();
          let a = document.createElement("a");
          let blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          let objectUrl = URL.createObjectURL(blob);
          a.setAttribute("href", objectUrl);
          a.setAttribute("download", "渠道数据.xlsx");
          a.click();
          URL.revokeObjectURL(a.objectUrl);
        }
      });
    },

    onSubmit () {
      post('/channelInfo/pushdata?beginTime=' + this.pushdataDate[0] + '&endTime=' + this.pushdataDate[1], {}).then(
        res => {
          this.$message({
            message: res.message,
            type: 'success'
          });
          this.pushdata = false
        })
    },
    checkpushdata (e) {
      get('/channelInfo/detail', {
        id: e.id
      }).then(res1 => {
        let channel = res1.data
        get('/channelInfo/checkpushdata', {
          'fullCode': channel.fullCode
        }).then(res => {
          let data = JSON.parse(res.data)[0]
          if (data.resdesc == 'ok' && data.subchannelkey !== "null") {
            this.$message({
              message: data.subchannelname + '已同步',
              type: 'success'
            });
          } else {
            let bigentime = channel.createTime
            let endtime = this.dateNew(new Date(bigentime).getTime() + 3600000)
            this.pushdataDate = [bigentime, endtime]
            post('/channelInfo/pushdata?beginTime=' + this.pushdataDate[0] + '&endTime=' + this.pushdataDate[
              1], {}).then(res => {
                console.log(res)
                this.$message({
                  message: channel.channelName + '同步成功',
                  type: 'success'
                });
                console.log('success')
              })
          }
        })
      })
    },
    dateNew (timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      // var D = date.getDate() + ' ';
      var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
      var h = date.getHours() + ':';
      var m = date.getMinutes() + ':';
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    init () {
      get('/channelInfo/listChannels', this.searchForm).then(res => {
        this.tableData = res.data.list
        this.searchForm.totalResult = res.data.total
      })
    },
    reset () {
      for (let key in this.searchForm) {
        this.searchForm[key] = ""
      }
      this.searchForm.parentId = this.$route.query.id
      this.searchForm.pageSize = 10
      this.searchForm.pageNum = 1
      this.init()
    },
    editClosedEvent ({
      row,
      column
    }) {
      const $table = this.$refs.xTable
      const field = column.property
      const cellValue = row[field]
      // 判断单元格值是否被修改
      if ($table.isUpdateByRow(row, field)) {
        setTimeout(() => {
          let param = {}
          param[field] = cellValue
          post('/channelInfo/update/' + row.id, row).then(res => {
            this.$message({
              message: res.message,
              type: 'success'
            });
          })
          // 局部更新单元格为已保存状态
          $table.reloadRow(row, null, field)
        }, 300)
      }
    },
    toEdit (e, type) {
      const routeUrl = this.$router.resolve({
        path: '/schemeV2/channelEdit',
        query: {
          id: e.id,
          'type': type
        }
      })
      window.open(routeUrl.href, '_blank')
    },
    copy (row) {
      let url = process.env.VUE_APP_BASE_h5;
      let oInput = document.createElement('input');
      oInput.value = `${url}${row.channelKey}`;
      document.body.appendChild(oInput);
      oInput.select(); // 选择对象;
      document.execCommand("Copy"); // 执行浏览器复制命令
      this.$message({
        message: '复制成功',
        type: 'success'
      });
      oInput.remove()
    },
    giveShort (row) {
      let stUrl = row.shortUrl
      if (stUrl) {
        let oInput = document.createElement('input');
        oInput.value = `https://v.mige.tv/${stUrl}`;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象;
        document.execCommand("Copy"); // 执行浏览器复制命令
        this.$message({
          message: '复制成功',
          type: 'success'
        });
        oInput.remove()
      } else {
        let url = process.env.VUE_APP_BASE_h5;
        let updata = {
          channel: row.channelKey,
          longUrl: `${url}${row.channelKey}`
        }
        post('/channelInfo/shorturl', updata).then(res => {
          let resUrl = res.data.shortCode
          let oInput = document.createElement('input');
          oInput.value = `https://v.mige.tv/${resUrl}`;
          document.body.appendChild(oInput);
          oInput.select(); // 选择对象;
          document.execCommand("Copy"); // 执行浏览器复制命令
          this.$message({
            message: '复制成功',
            type: 'success'
          });
          oInput.remove()
        })
      }
    },
    ewm (row) {
      let url = process.env.VUE_APP_BASE_h5;
      this.dialogVisible = true;
      this.$nextTick(function () {
        document.getElementById("qrcode").innerHTML = "";
        let qrcode = new QRCode("qrcode", {
          width: 300,
          height: 300,
          text: `${url}${row.channelKey}`
        });
      });
    },
    handlePageChange ({
      currentPage,
      pageSize
    }) {
      this.searchForm.pageNum = currentPage
      this.searchForm.pageSize = pageSize
      this.init()
    },
    handlePageChangeChannelog ({
      currentPage,
      pageSize
    }) {
      this.channelogParam.pageNum = currentPage
      this.channelogParam.pageSize = pageSize
      get('/channelInfo/channelogpage', this.channelogParam).then(res => {
        this.channelog = res.data.list
        this.channelogParam.totalResult = res.data.total
      })
    },
  }
}

</script>

<style scoped lang="scss">
.pageIndex {
  padding: 20px !important;

  .infoList {
    width: 100%;
    height: 50px;
    line-height: 50px;
    padding-left: 20px;
    border: 1px solid #409eff;
    background-color: #e1eefc;
    font-size: 13px;
    border-radius: 10px;
    // margin-top: 40px;
  }
}
</style>
