<template>
    <div class="app-container">
        <!-- 搜索向 -->
      <div class="flex">
          <div class="w_input">
            <span  class="textSpan">通道组名称:</span>
            <el-input v-model="body.groupName" style="width:200px" placeholder="通道名称" size="small" clearable />
            <el-button class="filter-item"  icon="el-icon-search" type="primary" plain @click="Search">搜索</el-button>
            <el-button class="classitem" style="marginRight:50px" type="primary" plain icon="el-icon-plus" @click="dataFormAdd">新增</el-button>
          </div>
      </div>


        <!-- 表格数据 -->
      <el-table v-loading="loading" :data="tableData" border style="width: 100%">
          <el-table-column label="序号" width="60" align="center">
                <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
                </template>
            </el-table-column>

          <el-table-column label="通道组名称" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                  <span>{{ scope.row.groupName }}</span>
              </template>
          </el-table-column>

          <el-table-column label="创建者" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                  <span type="text" >{{ scope.row.creator }}</span>
              </template>
          </el-table-column>

          <el-table-column label="创建时间" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                  <span>{{ scope.row.createTime }}</span>
              </template>
          </el-table-column>


          <el-table-column label="操作" fixed="right" width="200" align="center">
              <template slot-scope="scope">

                <!-- <el-button v-if="scope.row.isValid==0" size="small" icon="el-icon-circle-check" type="success"  @click="ModifyState(scope.row)">有效</el-button>
                <el-button v-if="scope.row.isValid==1" size="small" icon="el-icon-circle-close" type="info"  @click="ModifyState(scope.row)">无效</el-button> -->
                <el-button size="small" icon="el-icon-edit" type="warning" plain  @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" icon="el-icon-delete" type="danger" plain @click="ModifyDelete(scope.row,$event)">删除</el-button>
              </template>
          </el-table-column>
        
      </el-table>
        <!-- 分页 -->
      <div class="pagination">
      <el-pagination
        current-page.sync="body.current"
        :current-page="body.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="body.size"
        layout="total, sizes, prev, pager, next, jumper"
        background
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

     <!-- 新增与修改 -->
    <el-dialog :title="operation?'通道组新增':'通道组编辑'" :visible.sync="dialogFormVisible" width="85%" center>
      <el-form ref="dataForm" :model="dataForm" :rules="rules2" label-width="80px" size="small" label-position="right">
 
            <el-form-item label="通道组名称"  :label-width="formLabelWidth"  style="width:420px;margin:15px auto;paddingBottom:30px">
              <el-input v-model="dataForm.groupName" :disabled="!operation" placeholder="请输入通道组名称" />
            </el-form-item>
            <!-- 添加产品 -->
       <el-card  shadow="hover" v-if="!operation">
        <div slot="header" class="clearfix">
          <span class="topClass">分发组信息</span>
          
        </div>
        <div>
          <!-- 添加 -->
          <el-table  ref="multipleTable" :data="dataForm.distributeGroups">
          <!-- <el-table  ref="multipleTable" :data="dataForm.distributeGroups"  @selection-change="handleSelectionChange"> -->
             <!-- <el-table-column
                type="selection"
                width="55">
              </el-table-column> -->

          <el-table-column label="分发组名称" width="200" align="center" show-overflow-tooltip>
            <template slot-scope="scope" >
              <!-- <span >{{ scope.row.name }}</span>   -->
              <el-input v-model="scope.row.name" :disabled="scope.row.distributeGroupId != null" @keyup.enter.native="addGroup"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="策略" width="130" align="center">
            <template slot-scope="scope" >
              <!-- <el-input v-model="scope.row.policy" @keyup.enter.native="addGroup"></el-input> -->
              <div class="code"  v-if="selectref && scope.row.distributeGroupId != null" @click="onpolicy(scope.row)"></div>
              <el-select size="small"  v-model="scope.row.policy"  @click.native="inpolicy(scope.row)"  @change="clicktrue" @keyup.enter.native="addGroup"  placeholder="请选择" style="width: 100%" >
                  <el-option
                  v-for="item in distribute"
                  :key="item.policy"
                  :label="item.desc"
                  :value="item.policy"
                  />
                </el-select>
              <!-- <el-select size="small"  v-model="scope.row.policy" v-else @click.native="inpolicy(scope.row)"  @keyup.enter.native="addGroup"  placeholder="请选择运营商" style="width: 100%" >
                  <el-option
                  v-for="item in distribute"
                  :key="item.policy"
                  :label="item.desc"
                  :value="item.policy"
                  />
                </el-select> -->
              <!-- <span >{{ scope.row.policy }}</span>   -->
            </template>
          </el-table-column>
          
          <el-table-column label="运营商" align="center" show-overflow-tooltip>
            <template slot-scope="scope" >
              <el-select size="small" v-model="scope.row.operator" @change="operatorClick(scope.row)"  :disabled="scope.row.distributeGroupId != null" @keyup.enter.native="addGroup"  placeholder="请选择运营商" style="width: 90%" >
                  <el-option
                  v-for="item in dataOperator"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  />
                  </el-select>
            </template>
          </el-table-column>

          <el-table-column label="通道" align="center" show-overflow-tooltip>
            <template slot-scope="scope" >
              <!-- <span >{{ scope.row.channel }}</span>   -->
              <el-tooltip class="item" effect="dark" content="配置通道" placement="top" v-if="scope.row.channels == undefined || scope.row.channels.length <= 0 ">
                <el-button type="primary" plain icon="el-icon-plus" @click ="onwarning(scope.row)" circle > </el-button>
              </el-tooltip> 
              <el-tooltip class="item" effect="dark" content="查看通道" placement="top" v-else>
                <el-button type="primary" plain icon="el-icon-view" @click ="onwarning(scope.row)" circle > </el-button>
              </el-tooltip>        
            </template>
          </el-table-column>

          <el-table-column label="排序" align="center"  show-overflow-tooltip>
            <template slot-scope="scope" >
              <el-input v-model="scope.row.weight" @keyup.enter.native="addGroup"></el-input>
              <!-- <span>{{scope.row.weight}}</span>   -->
            </template>
          </el-table-column>

          <el-table-column label="是否有效"  align="center" show-overflow-tooltip >
            <template slot-scope="scope">
              <!-- <span v-if="scope.row.isValid == 1">有效</span>
              <span v-if="scope.row.isValid == 0">无效</span> -->
               <el-select size="small" v-model="scope.row.isValid" @keyup.enter.native="addGroup"  placeholder="请选择是否有效" style="width: 90%" >
                  <el-option
                  v-for="item in status"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  />
                  </el-select>
            </template>
          </el-table-column>

          <el-table-column label="操作"  width="165" min-width="150" align="center">
              <template slot-scope="scope">
                 <!-- <el-tooltip class="item" effect="dark" content="编辑分发组" placement="top">
                   <el-button  type="primary" plain icon="el-icon-edit" circle @click="priceEdie(scope.row,scope.$index,$event)"></el-button>
                 </el-tooltip> -->
                 <el-tooltip class="item" effect="dark" content="删除分发组" placement="top">
                    <el-button type="danger" plain icon="el-icon-delete" circle  @click="priceDelete(scope.row,scope.$index,$event)"></el-button>  
                 </el-tooltip>
                      <el-tooltip placement="top" effect="light" style="padding: 10px; 0 0 0">
                            <div slot="content">
                                <p>分发组信息:</p>
                                <p>其中不能有为空的操作！！！</p>
                                </div>
                            <i class="el-icon-warning" />
                            </el-tooltip>
              </template>
            </el-table-column>
        </el-table>
        <el-button class="addGroupButton" type="primary" round plain @click="addGroup(dataForm)">添加分发组</el-button>
        </div>
       </el-card>
 

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="buttonLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加分发组 -->
     <!-- <el-dialog :title="group?'分发组新增':'分发组编辑'" :visible.sync="groupVisible" :close-on-click-modal="false" width="45%" center>
      <el-form ref="infoForm" :model="infoForm" :rules="rules2" label-width="80px" size="small" label-position="right">
  
            <el-form-item label="分发组名称" prop="name" :label-width="formLabelWidth"  >
              <el-input v-model="infoForm.name" placeholder="请输入分发组名称" />
            </el-form-item>

            <el-form-item label="策略" prop="policy" :label-width="formLabelWidth"  >
        
                <el-col :span="12">
                   <el-input v-model="infoForm.policy" placeholder="请输入策略" />
                </el-col>
                <el-col :span="2" style="marginLeft:10px">
                 <el-tooltip class="item" effect="dark" content="配置通道" placement="top">
                   <el-button type="primary" plain icon="el-icon-plus" @click ="onwarning" circle > </el-button>
                 </el-tooltip> 
                 </el-col>
            </el-form-item>

            <el-form-item label="运营商" prop="channel" :label-width="formLabelWidth" >
              <el-select size="small" v-model="infoForm.operator"  placeholder="请选择是否有效" style="width: 100%" >
                  <el-option
                  v-for="item in dataOperator"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  />
                  </el-select>
            </el-form-item>
      
            <el-form-item label="排序" prop="name" :label-width="formLabelWidth"  >
              <el-input v-model="infoForm.weight" placeholder="请输入排序" />
            </el-form-item>

            <el-form-item label="是否有效" prop="channel" :label-width="formLabelWidth" >
               <el-select size="small" v-model="infoForm.isValid"  placeholder="请选择是否有效" style="width: 100%" >
                  <el-option
                  v-for="item in status"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  />
                  </el-select>
            </el-form-item>

      </el-form>
      <div slot="footer" class="dialogFooter">
        <el-button @click="groupVisible = false">取 消</el-button>
        <el-button type="primary" @click="GroupSubmitForm">确 定</el-button>
      </div>
    </el-dialog> -->

    <!-- 给分发组添加通道 -->
    <el-drawer
      title="通道"
      style="width:150%"
      :before-close="handleClose"
      :visible.sync="GroupDialog"
      direction="ltr"

      >
      <div class="demo-drawer__content">
               <el-table :data="infoForm.channels" >
                    <el-table-column label="通道名称"  align="center"  show-overflow-tooltip>
                      <template slot-scope="scope" >
                        <!-- <el-input v-model="scope.row.channelName" @keyup.enter.native="onAddChannel"></el-input>  channelInfosList -->
                        <el-select size="small" v-model="scope.row.channelId" filterable  @keyup.enter.native="onAddChannel" style="width: 90%" >
                        <el-option
                        v-for="item in channelInfosList"
                        :key="item.channelId"
                        :label="item.channelName"
                        :value="item.channelId"
                        />
                        </el-select>
                      </template>
                    </el-table-column>

                    <el-table-column label="权重" width="120" align="center" show-overflow-tooltip>
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.weight"  @keyup.enter.native="onAddChannel"></el-input>
             
                      </template>
                    </el-table-column>

                    <el-table-column label="操作" width="120"  align="center">
                        <template slot-scope="scope">
                          <el-button type="danger" icon="el-icon-delete" plain @click="CardsDelete(scope.row,scope.$index,$event)" circle></el-button>
                        </template>
                      </el-table-column>
               </el-table>
               <el-button style="width:90%;margin:15px"  type="primary" round plain @click="onAddChannel">添加通道</el-button>
        <!-- <div class="dialogFooterl">
          <el-button @click="GroupDialog = false">取 消</el-button>
          <el-button type="primary"  @click="handleClose">确定</el-button>
        </div> -->
      </div>
    </el-drawer>
    
    </div>
</template>

<script>
import api from '@/api/channelGroup.js'
// import { delete } from 'vuedraggable'
export default {
    data(){
        return{  
            loading:false,   //表格数据加载
            tableData:[],       //表格数据
            buttonLoading:false,
            body:{
                size:10,
                current:1,
                groupName:""   //名称搜索
            },
            total:0,
            dataForm:{
              distributeGroups:[
                {}
              ]
            },
            infoForm:{

            },
            rules2:{},
            operation:false,
            group:false,
            dialogFormVisible:false,
            groupVisible:false,
            GroupDialog:false,
            formLabelWidth:"120px",
            dataOperator:[
              {id:1,name:"移动"},
              {id:2,name:"联通"},
              {id:3,name:"电信"},
            ],
            dataPolicy:[
              {
                id:1,name:"成本优先",
              },
              {
                id:2,name:"成功率"
              }
            ],
             status:[{
                id:1,
                name:"有效"
            },{
                id:0,
                name:"无效"
            }],
            distribute:[],    //策略
            channelInfosList:[],     //通道
            selectref:true

        }
    },
    created(){
        this.reLoad()
        this.distributeGroup()
    },
    methods:{
         // 重载数据
        reLoad(){
            this.loading = true
            api.channelGroupList(this.body).then((res) => {
                this.loading = false
                let list = res.data.data.records
                this.tableData = list
                this.total = res.data.data.total
            })
        },
        //获取策略
        distributeGroup(){
          api.distributeGroup().then((res)=>{
            this.distribute = res.data.data
          })
        },

        //选择策略
        onpolicy(row){
          this.selectref = true
          console.log(row.distributeGroupId)
          if(row.distributeGroupId){
             this.$confirm('此操作将修改策略, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showClose:false,
                closeOnClickModal:false,
                type: 'warning'
              }).then(() => {
                 this.selectref = false
                 console.log("确定")
              }).catch(() => {
                this.selectref = true
              });
          console.log(11)
          }else{
            this.selectref = false
          console.log(22)
          }
        },
        clicktrue(){
          this.selectref = true
        },
        inpolicy(row){
          this.selectref = true
          if(row.distributeGroupId){
          this.selectref = true
          console.log(1)
          }else{
            this.selectref = false
            console.log(2)
          }
        },
        //添加分发组
        addGroup(row){
            this.selectref = true
          this.group =true
          this.groupVisible = true
          if(this.dataForm.distributeGroups == null){
            this.dataForm.distributeGroups = []
          }
           let object = {
             channelGroupId:row.channelGroupId,
             channels:[],
             isValid:1,
             name:"",
             operator:"",
             policy:"",
             weight:""
           }
            this.dataForm.distributeGroups.push(object)
          //  this.infoForm = {}
        },
        //编辑分发组
        priceEdie(row){
          this.group = false
          this.groupVisible = true
          this.infoForm = row
        },
          //添加分发组
          // GroupSubmitForm(){
          //   if(this.group){
          //     this.dataForm.distributeGroups.push(this.infoForm)
          //     this.groupVisible = false
          //   }else{
          //     this.groupVisible = false
          //   }
          // },
       //策略通道
        onwarning(row){
          if(row.operator){
            this.infoForm = row
            this.GroupDialog = true
            const params = new URLSearchParams()
            params.append('operator', row.operator)
            api.getAllChannelnfos(params).then((res)=>{
               this.channelInfosList = res.data.data
            })
          }else{
            this.$message({
                type: 'error',
                message: "请先选择运营商"
            })
          }
          // if(this.infoForm.channelInfos == undefined || this.infoForm.channelInfos.length == 0){
          //   this.infoForm.channelInfos = [
          //     {
          //       channelName :"",
          //       weight:""
          //     }
          //   ]
          // }
        },
          handleClose(done) {
            this.GroupDialog = false
            // this.$confirm('确定要提交表单吗？')
            //   .then(_ => {
            //       this.GroupDialog = false
            //   })
            //   .catch(_ => {});
          },
          operatorClick(row){
            row.channels = []
          },
          //添加分发组通道
          onAddChannel(){
            let object = {
              channelId :"",
              weight:""
            }
            this.infoForm.channels.push(object)
          },
          //删除分发组
          priceDelete(row,index,e){
            // row.splice(index,1)

            if(row.distributeGroupId){
              this.$confirm('是否删除该分发组', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                    }).then(()=>{
                        api.distributeGroupDelete(row.distributeGroupId).then((res)=>{
                            this.dataForm. distributeGroups.splice(index,1)
                            this.reLoad()
                            this.$message({
                                type: 'success',
                                message: '删除成功'
                              })
                          })
                    }).catch(() => {
                    this.$message({
                      type: 'info',
                      message: '已取消'
                    });          
              });
            }else{
                this.dataForm.distributeGroups.splice(index,1)
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
            }
          
              let target=e.target;
            if(target.nodeName == 'SPAN' || target.nodeName == 'I'){
              target = e.target.parentNode;
            }
            target.blur(); 
          },
          //删除分发组中的通道
           CardsDelete(row,index,e){
            let relationId=this.dataForm.relationId
                if(row.id){
                   this.$confirm('是否删除该通道', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                    }).then(()=>{
                      api.channelnfosdelete(row.id).then((res)=>{
                        this.reLoad()
                        this.infoForm.channels.splice(index,1)
                        this.$message({
                            type: 'success',
                            message: '删除成功'
                          })
                      })
                      }).catch(() => {
                        this.$message({
                          type: 'info',
                          message: '已取消'
                        });          
                      });
                      
                }else{
                    this.infoForm.channels.splice(index,1)
                    this.$message({
                        type: 'success',
                        message: '删除成功'
                      })
                }
   
            let target=e.target;
            if(target.nodeName == 'SPAN' || target.nodeName == 'I'){
                  target = e.target.parentNode;
            }
            target.blur();  
        },
        //搜索数据
        Search(){
            this.body.current = 1
            this.reLoad()
        },
        //新增和修改API
        submitForm(){
          this.$refs['dataForm'].validate((valid) => {
                  if (valid) {
                    if (!this.operation) {
                        let dataForm = this.dataForm
                      // 编辑
                         this.$confirm('确认是否提交, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        // showClose:false,
                        // closeOnClickModal:false,
                        type: 'warning'
                      }).then(() => {
                         this.buttonLoading = true
                          api.channelGroupUpdate(dataForm).then(response => {
                            this.buttonLoading = false
                            if (response.data.status == '200') {
                              this.$message({
                                type: 'success',
                                message: '操作成功'
                              })
                              this.dialogFormVisible = false
                              this.reLoad()
                            } else {
                               this.$message({
                                type: 'error',
                                message: response.data.msg
                              })
                            }
                          })
                        .finally(() => this.buttonLoading = false)
                      })
                    } else {
                    //   // 添加
                       this.buttonLoading = true
                         api.channelGroupAdd(this.dataForm).then(response => {
                              if (response.status === 200) {
                                this.$message({
                                  type: 'success',
                                  message: '操作成功'
                                })
                                this.dialogFormVisible = false
                                this.reLoad()
                              } else {
                                this.$message({
                                  type: 'error',
                                  message: response.data.msg
                                })
                              }
                            })
                          .finally(() => 
                          setTimeout(()=>{
                            this.buttonLoading = false
                          },1600)
                          )
                    }
                  }
                })
        },
        //新增弹框
        dataFormAdd(){
            this.operation = true // true:新增, false:编辑
            this.dialogFormVisible = true // 控制弹出框
            this.dataForm = {}
            if(this.$refs['dataForm']){
                 this.$refs['dataForm'].resetFields();
            }
           
        },
        //编辑弹框
        handleEdit(row){
           this.operation = false // true:新增, false:编辑
           this.dialogFormVisible = true // 控制弹出框 
          //  row.distributeGroups = [
          //    {name:"ck分发组",policy:1,channelInfos:[],operator:2,weight:"99",isValid:1}
          //  ]
           this.dataForm = JSON.parse(JSON.stringify(row)) 
           if(this.$refs['dataForm']){
               this.$refs['dataForm'].resetFields();
           }
        },
          //删除API
        ModifyDelete(row,e){
            const that = this
            let target=e.target;
            if(target.nodeName == 'SPAN' || target.nodeName == 'I'){
                  target = e.target.parentNode;
            }
            target.blur();
            that.$confirm('此操作将删除通道：' + row.groupName, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            .then(() => {
                api.channelGroupIdDelete(row.channelGroupId).then((res)=>{
                     if (res.status === 200) {
                        that.$message({
                            type: 'success',
                            message: '删除成功'
                        })
                        that.reLoad()
                     } else {
                        that.$message({
                            type: 'error',
                            message: res.data.message
                        })
                     }
                })
            })    
        },
        ///分页
        handleSizeChange: function(val) {
            this.body.size = val
            this.reLoad()
        },
        handleCurrentChange: function(val) {
            this.body.current = val
            this.reLoad()
        }
    }
}
</script>

<style scoped>
    .flex{
     width: 90%;
     display: flex;
     flex-direction: row;
     margin-bottom: 10px;
     /* flex-wrap: wrap; */
     justify-content: flex-start;
    }
    .flexend{
    display: flex;
    justify-content: flex-end;
    /* padding-right: 2rem; */
    width: 100%;
    /* margin: 0 auto; */
    padding-bottom: 20px;
    }
    .el-card {
    border: 0px solid #e6ebf5;
    margin-top: 20px;
    }
    .dialogFooterl{
     float: right;
     margin-top: 35px;
     margin-right: 35px;
    }
    .addGroupButton{
      width: 80%;
      margin: 30px 10px 10px 90px;
      text-align: center;

    }
      :focus {
          outline: 0;
        }
    .code{
      position: absolute;
      top: 0;
      width: 90%;
      height: 90%;
      /* border: 1px solid red; */
      z-index: 20;
    }
</style>