<template>
  <div style="padding:20px">
    <el-form :inline="true" 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-input v-model="searchForm.unicomContacts" placeholder="负责人" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="init()">搜索</el-button>
        <el-button type="primary " icon="el-icon-plus" plain @click="channelShow = true">新增二级渠道</el-button>
        <el-button @click="reset('searchForm')">刷新</el-button>
        <el-button type="info" @click="toSubChannel">三级渠道查询</el-button>
      </el-form-item>
    </el-form>

    <div style="margin:30px 0">
      <el-table max-height="700" border highlight-current-row :data="tableData" :header-cell-style="{ 'background-color': '#E4E7ED', color: '#000' }" style="width: 100%;">
        <el-table-column prop="channelName" label="一级渠道名称" />
        <el-table-column prop="unicomContacts" label="负责人" />
        <el-table-column prop="channelPartner" label="合作方" />
        <el-table-column prop="standardFullCode" label="标准渠道编码" />
        <el-table-column prop="channelCode" 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 label="状态管理">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.channelStatus" :active-value="1" :inactive-value="0" active-text="生效" inactive-text="失效" @change="switchChange($event,scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="onlineTime" label="生效时间" />
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="toView(scope.row)">查询</el-button>
            <el-button type="text" size="small" @click="toEdit(scope.row)">编辑</el-button>
            <!-- <el-button type="text" size="small" @click="del(scope.row)">删除</el-button> -->
            <!-- <el-button type="text" size="small" @click="invalid(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="totalResult" :page-size="searchForm.pageSize">
        </el-pagination>
      </div>
    </div>

    <!-- 新增二级渠道弹窗 -->
    <el-dialog title="新建二级渠道" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="channelShow" width="55%" top="5vh" :before-close="closeAdd">
      <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="closeAdd">取 消</el-button>
        <el-button type="primary" @click="isEdit==0?addChannel():editChannel()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { post, get } from '@/api/common'
const XEUtils = require("xe-utils");
export default {
  name: 'Channel',
  data () {
    return {
      //  搜索相关内容
      searchForm: {
        channelName: '',
        channelPartner: '',
        parentId: 0,
        pageNum: 1,
        pageSize: 10,
        unicomContacts: ""
      },
      totalResult: 0,
      // 表格数据
      loading: false,
      tableData: [],
      strategyStatus: [
        { label: '生效中', value: '1' },
        { label: '未生效', value: '0' }
      ],
      strategyType: [
        { label: '基本策略', value: '0' },
        { label: '活动策略', value: '1' }
      ],
      channelShow: false,
      form: {
        channelName: "",//渠道名称
        channelCodeOne: "6602", //一级编码
        onlineTime: "",//上线时间
        channelPartner: "",//合作方
        partnerContacts: "",//合作方联系人
        partnerPhone: "",//合作方联系方式
        unicomContacts: "",//联通负责人
        unicomPhone: "",//联通负责人电话
        apiUrl: "",//外部接口
        channelStatus: 1,
        onOffStatus: 1,
        channelTag: 2,
      },
      rules: {
        channelName: [{ required: true, message: '请输入渠道名称', trigger: 'blur' }],
        channelCodeOne: [{ required: true, message: '一级渠道编码不能为空', trigger: 'blur' },{ min: 4, max: 4, message: '一级渠道编码必须为4位', 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' }],
      },
      isEdit: 0,
      channelId: "",
      oldForm: {},
      updateForm: {}
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    closeAdd () {
      this.isEdit = 0
      this.channelShow = false
      for (let key in this.form) {
        this.form[key] = ""
      }
      this.form.channelTag = 2
      this.form.channelCodeOne = '6602'
      this.form.channelStatus = 1
      this.form.onOffStatus = 1
    },
    // 新增二级渠道
    addChannel () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          post('/channelInfo/create', this.form).then(res => {
            if (res.code == 10000) {
              this.$message.success('创建成功!')
              this.closeAdd()
              this.init()
            }
            // console.log(res)
          })
        }
      })
    },
    editChannel () {
      for (let key in this.form) {
        this.updateForm[key] = this.form[key]
      }
      var array1 = this.oldForm;
      var array2 = this.updateForm;
      let text = '渠道：' + this.updateForm.channelName
      // console.log(this.updateForm)
      XEUtils.objectEach(array2, (item, key) => {
        if (item != array1[key]) {
          text += `\n${key}:${array1[key]} 改为 ${item}`;
        }
      })
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.updateForm.channelTag = 2
          if (this.updateForm.channelCodeTwo == '0') {
            this.updateForm.channelCodeTwo = ""
          }
          post('/channelInfo/update/' + this.channelId, this.updateForm).then(res => {
            this.$message.success('修改成功!')
            post('/channelInfo/createChannlelog', {
              'type': 2,
              'notes': text,
              'channelId': this.channelId
            })
            this.closeAdd()
            this.init()
          })
        }
      })
    },
    switchChange (e, row) {
      let text = '渠道：' + row.channelName + `\n onOffStatus: 改为 ${e}`
      post('/channelInfo/createChannlelog', {
        'type': 2,
        'notes': text,
        'channelId': row.id
      }).then(res => {
        let formData = new FormData()
        formData.append("id", row.id)
        formData.append("status", e)
        post('/channelInfo/ffectiveOrFailure', formData).then(res => {
          if (res.code == 10000) {
            this.init()
          }
        })
      })

    },
    handleSizeChange (val) {
      this.searchForm.pageSize = val
      this.searchForm.pageNum = 1
      this.init()
    },
    handleCurrentChange (val) {
      this.searchForm.pageNum = val
      this.init()
    },
    init () {
      get('/channelInfo/page', this.searchForm).then(res => {
        this.tableData = res.data.list
        this.totalResult = res.data.total
      })
    },
    reset (formName) { // 重置
      this.searchForm = {
        channelName: '',
        channelPartner: '',
        parentId: 0,
        pageNum: 1,
        pageSize: 10,
        unicomContacts: ""
      },
        this.init()
      // get('/channelInfo/page', {}).then(res => {
      //   this.tableData = res.data.list
      // })
    },
    toView (e) {
      const routeUrl = this.$router.resolve({ path: '/schemeV2/channelView', query: { id: e.id } })
      window.open(routeUrl.href, '_blank')
    },
    toEdit (e) {
      console.log(e)
      this.channelId = e.id
      this.isEdit = 1
      for (let key in this.form) {
        this.form[key] = e[key]
      }
      if(e.channelCodeOne == '0' || e.channelCodeOne == null||e.channelCodeOne == ''){
        this.form.channelCodeOne = '6602'
      }
      // if(this.form.channelCodeOne == '0'){
      //   this.form.channelCodeOne ="9002"
      // }
      this.updateForm = e
      this.oldForm = JSON.parse(JSON.stringify(e))
      this.channelShow = true
      // const routeUrl = this.$router.resolve({ path: '/schemeV2/channelEdit', query: { id: e.id } })
      // window.open(routeUrl.href, '_blank')
    },
    toSubChannel (e) {
      const routeUrl = this.$router.resolve({ path: '/schemeV2/channelSubList', query: { id: e.id } })
      window.open(routeUrl.href, '_blank')
    },

    del (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        post('/channelInfo/delete', { 'ids': [row.id] }).then(res => {
          this.init()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style lang="scss">
.searchBox {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: #bfbfbf 0 0 2px;
  height: unset !important;
  padding: 10px 10px;

  form {
    margin: auto;

    .el-form-item {
      margin: 5px 5px;
    }
  }
}

.tableBox {
  margin-top: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: #bfbfbf 0 0 2px;

  .block {
    .el-pagination {
      margin-top: 30px;
      float: right;
    }
  }
}
</style>
