<template>
  <div>
    <el-container>
      <el-main>
        <template v-if="form.parentId || $route.query.type == 'erji'">
          <el-form ref="form" :model="form" :rules="ruless" label-width="160px">
            <el-form-item label="渠道名称" prop="channelName">
              <el-input placeholder="请输入内容" v-model="form.channelName" clearable @change="changeInputer"></el-input>
            </el-form-item>
            <el-form-item label="一级渠道">
              <el-select v-model="form.parentId" filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loading">
                <el-option v-for="item in options" :key="item.id" :label="item.channelName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级编码">
              <el-input placeholder="自动生成" v-model="form.channelCode" disabled @change="changeInput"></el-input>
            </el-form-item>
            <el-form-item label="完整编码">
              <el-input placeholder="自动生成" v-model="form.fullCode" disabled @change="changeInput"></el-input>
            </el-form-item>
            <el-form-item label="key">
              <el-input placeholder="自动生成" v-model="form.channelKey" disabled @change="changeInput"></el-input>
            </el-form-item>
            <el-form-item label="渠道类别" prop="channelType">
              <el-select v-model="form.channelType" clearable placeholder="请选择">
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上线时间">
              <el-col :span="11">
                <el-date-picker type="datetime" placeholder="选择日期" v-model="form.onlineTime" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
                </el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="策略类型">
              <el-radio @change="radioClick(1)" v-model="form.onOffStatus" :label="1">新策略</el-radio>
              <el-radio @change="radioClick(2)" v-model="form.onOffStatus" :label="2">旧策略</el-radio>
            </el-form-item>

            <el-form-item v-if="form.onOffStatus!==0" label="绑定策略" prop="strategyId">
              <el-select v-model="form.strategyId" filterable clearable placeholder="请选择策略" :loading="loading">
                <el-option v-for="item in celueList" :key="item.id" :label="item.strategyName" :value="item.id">
                </el-option>
              </el-select>
              <span style="margin-left: 20px">
                <vxe-button @click="refreshClick" 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="form.strategyId" style="margin-left: 20px">
                <vxe-button @click="toEdit(form.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="form.adStrategyId">
                <el-option v-for="item in adStrategyList" :label="item.name" :key="item.id" :value="item.id"></el-option>
              </el-select>
            </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-item label="开启WO186域名">
              <el-radio v-model="form.wotv" label="0">关闭</el-radio>
              <el-radio v-model="form.wotv" label="1">开启</el-radio>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="onSubmit('form')">立即创建</el-button>
              <el-button @click="close">关闭</el-button>
            </el-form-item>
          </el-form>
        </template>

        <template v-else>
          <el-form ref="form" :model="form" :rules="rules" label-width="160px">
            <el-form-item label="渠道名称" prop="channelName">
              <el-input placeholder="请输入内容" v-model="form.channelName" clearable @change="changeInput"></el-input>
            </el-form-item>
            <el-form-item label="一级编码">
              <el-input disabled v-model="form.channelCode"></el-input>
            </el-form-item>
            <el-form-item label="上线时间">
              <el-col :span="11">
                <el-date-picker type="datetime" placeholder="选择日期" v-model="form.onlineTime" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
                </el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="合作方">
              <el-input v-model="form.channelPartner"></el-input>
            </el-form-item>
            <el-form-item label="合作方联系人">
              <el-input v-model="form.partnerContacts"></el-input>
            </el-form-item>
            <el-form-item label="合作方联系方式">
              <el-input v-model="form.partnerPhone"></el-input>
            </el-form-item>
            <el-form-item label="负责人姓名">
              <el-input v-model="form.unicomContacts"></el-input>
            </el-form-item>
            <el-form-item label="负责人电话">
              <el-input v-model="form.unicomPhone"></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-item>
              <el-button type="primary" @click="onSubmit('form')">立即创建</el-button>
              <el-button @click="close">关闭</el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import {
  post,
  get
} from '@/api/common'
import XEUtils from 'xe-utils'
var text = '';
export default {
  name: 'SchemeEdit',
  data () {
    return {
      // 高级策略列表
      adStrategyList: [],
      form: {
        channelPattern: '1',
        channelStatus: 1,
        onOffStatus: 0,
        adStrategyId: "",
        strategyId: ""
      },
      oldform: {},
      id: null,

      options: [],
      loading: false,

      celueList: [],

      typeList: [{
        value: '集团渠道',
        label: '集团渠道'
      },
      {
        value: '省分线下渠道',
        label: '省分线下渠道'
      },
      {
        value: '省分线上渠道',
        label: '省分线上渠道'
      },
      {
        value: '互联网渠道',
        label: '互联网渠道'
      },
      {
        value: '自有线上渠道',
        label: '自有线上渠道'
      },
      {
        value: '社会代理和其他渠道',
        label: '社会代理和其他渠道'
      }
      ],

      rules: {
        channelName: [{
          required: true,
          message: '请输入渠道名称',
          trigger: 'blur'
        }]
      },
      ruless: {
        channelName: [{
          required: true,
          message: '请输入渠道名称',
          trigger: 'blur'
        }],
        strategyId: [{
          required: true,
          message: '请选择渠道名称',
          trigger: 'change'
        }],
        channelType: [{
          required: true,
          message: '请选择渠道类型',
          trigger: 'change'
        }]

      }
    }
  },
  created () {
    document.title = '新增渠道'
    let that = this
    this.id = this.$route.query.id
    if (this.id) {
      get('/channelInfo/detail', {
        'id': this.id
      }).then(res => {
        that.oldform = JSON.parse(JSON.stringify(res.data))
        if (this.$route.query.type == 'erji') {
          this.oldchannelName = that.oldform.channelName
          delete this.form.id
          delete this.form.channelName
          delete this.form.channelKey
          delete this.form.fullCode
          delete this.form.channelCode
          this.form.parentId = this.id * 1
        } else {
          this.form = res.data
          if (this.form.onOffStatus === 1) {
            get('/strategytemplate/list', {
              pageNum: 1,
              pageSize: 99999,
            }).then(res => {
              this.celueList = res.data.list
            })
          } else {
            this.refresh()
          }

        }
      })

    }
    // 获取一级渠道列表
    get('/channelInfo/page', {
      parentId: 0,
      'pageSize': 9999,
      'pageNum': 1
    }).then(res => {
      this.options = res.data.list
    })
  },
  mounted () {
    this.getAdStrategyidList()
  },
  methods: {
    // 获取高级策略列表
    getAdStrategyidList () {
      get('/strategysenior/list', { pageNum: 1, pageSize: 99999 }).then(res => {
        this.adStrategyList = res.data.list
      })
    },
    // 刷新策略列表
    refreshClick () {
      if (this.form.onOffStatus === 1) {
        get('/strategytemplate/list', {
          pageNum: 1,
          pageSize: 99999,
        }).then(res => {
          this.celueList = res.data.list
        })
      } else {
        this.refresh()
      }
    },
    // 切换新旧策略
    radioClick (num) {
      this.form.strategyId = ''
      if (num === 2) {
        this.refresh()
      } else {
        get('/strategytemplate/list', {
          pageNum: 1,
          pageSize: 99999,
        }).then(res => {
          this.celueList = res.data.list
        })
      }

    },
    onSubmit (formName) {
      this.$confirm('此操作将永久改变数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.form.onOffStatus === 0 && this.$route.query.type == 'erji') {
          this.$message.error('请选择策略类型!')
          return false
        }
        var array1 = this.oldform;
        var array2 = this.form;
        let text = '渠道：' + this.form.channelName
        XEUtils.objectEach(array2, (item, key) => {
          if (item != array1[key]) {
            text += `\n${key}:${array1[key]} 改为 ${item}`;
          }
        })
        let type = 1
        let channelId = this.id
        if (this.form.parentId || this.$route.query.type == 'erji') {
          type = 2
          channelId = this.form.parentId
        }
        post('/channelInfo/createChannlelog', {
          'type': type,
          'notes': text,
          'channelId': channelId
        })
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.id && !this.$route.query.type) {
              post('/channelInfo/update/' + this.id, this.form).then(res => {
                this.$message({
                  message: res.message,
                  type: 'success',
                  duration: 3000,
                  offset: 360
                });
                setTimeout(() => {
                  window.close()
                }, 1200)
              })
            } else {
              post('/channelInfo/create', this.form).then(res => {
                this.$message({
                  message: res.message,
                  type: 'success',
                  duration: 3000,
                  offset: 360
                })
                setTimeout(() => {
                  window.close()
                }, 1200)
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    changeInput () {
      this.form.channelName = this.form.channelName.includes("H5") ? this.form.channelName :
        `${this.form.channelName}H5`
      // this.$set(this.form,'name',`${newV}H5`)
    },
    changeInputer () {
      this.form.channelName = `${this.oldchannelName || ''}${this.form.channelName}`
      // this.$set(this.form,'name',`${newV}H5`)
    },
    close () {
      this.$confirm('此操作不会保存已编辑数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href = 'about:blank'
        window.close()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    toAdd () {
      if (this.form.onOffStatus === 1) {
        let routeUrl = this.$router.resolve({
          path: '/strategy/add'
        })
        window.open(routeUrl.href, '_blank')
      } else {
        let routeUrl = this.$router.resolve({
          path: '/schemeV2/schemeAdd'
        })
        window.open(routeUrl.href, '_blank')
      }

    },
    toEdit (e) {
      if (this.form.onOffStatus === 1) {
        const routeUrl = this.$router.resolve({
          path: '/strategy/add',
          query: {
            id: e,
            editId: 1
          }
        })
        window.open(routeUrl.href,'_blank')
      } else {
        const routeUrl = this.$router.resolve({
          path: '/schemeV2/schemeAdd',
          query: {
            id: e
          }
        })
        window.open(routeUrl.href, '_blank')
      }

    },
    refresh () {
      get('/strategyInfoNew/page', {
        'strategyType': 0,
        'pageSize': 9999,
        'pageNum': 1,
        'strategyType': 0
      }).then(res => {
        this.celueList = res.data.list
      })
    },
    remoteMethod (query) {
      let that = this
      if (query !== '') {
        this.loading = true;
        get('/channelInfo/page', {
          parentId: 0,
          channelName: query
        }).then(res => {
          this.loading = false;
          that.options = res.data.list
        })
      } else {
        this.options = [];
      }
    },
    remoteMethodstrategyId (query) {
      let that = this
      if (query !== '') {
        this.loading = true;
        get('/strategyInfoNew/page', {
          strategyName: query,
          'pageSize': 9999,
          'pageNum': 1,
          'strategyType': 0
        }).then(res => {
          this.loading = false;
          that.celueList = res.data.list
        })
      } else {
        this.options = [];
      }
    }
  }
}

</script>

<style scoped>
</style>
