<template>
  <div class="yqrange-index-wrapper">
    <!--<bread-crumb :curmbFirst="curmbFirst"></bread-crumb>-->
    <div class="yqrange-index-content" id="screenSet">
      <!--<div class="header-title">云鹊专区</div>-->

      <!-- <el-form ref="settingForm" :model="settingForm"
               label-width="150px"
               label-suffix="："
               class="basic-form">

        <div v-for="(item, index) in settingForm.settingData" :key="index" display:inline>
          <el-form-item :label="item.appType">
            <el-radio-group size="small" v-model="item.showOff">
              <el-radio :label="1">开启</el-radio>
              <el-radio :label="0">关闭</el-radio>
            </el-radio-group>

            <el-input v-model="item.appName" style="width:120px;margin-left:40px;" size="small" placeholder="重命名"/>

            <el-input v-model="item.seqNo" style="width:60px;margin-left:40px;" size="small" placeholder="序号"/>
          </el-form-item>
        </div>
      </el-form> -->

      <el-table :data="settingForm.settingData" class="customer-table" style="margin-left:70px;"
        :header-cell-style="{background:'#ffffff'}">
        <el-table-column label="" prop="appType" width="150"></el-table-column>
        <el-table-column label="" width="180">
          <template slot-scope="scope">
            <el-radio-group size="small" v-model="scope.row.showOff">
              <el-radio :label="1">开启</el-radio>
              <el-radio :label="0">关闭</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column label="重命名" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.appName" style="width:120px;" :maxlength="6" size="small" placeholder="重命名"/>
          </template>
        </el-table-column>
        <el-table-column label="序号" width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.seqNo" style="width:60px;" size="small" @blur="BlurText($event)" @placeholder="序号"/>
          </template>
        </el-table-column>

        <el-table-column label="选择积木页（仅支持图片搭建的积木页和跳转）" width="320">
          <template slot-scope="scope">
            <el-select filterable v-if="scope.row.appTag == 10" v-model="scope.row.appUrl" placeholder="请选择积木页" style="position: relative;width:75%;">
              <el-option
                style="position: relative;"
                v-for="item2 in settingForm.activityList"
                :key="item2.id"
                :label="item2.title"
                :value="item2.id">
              </el-option>
            </el-select>
<!--              <img v-if="scope.row.appTag == 10"-->
<!--                @click="add(scope.$index)"-->
<!--                class="edit-img"-->
<!--                src="../../assets/image/plus.png"-->
<!--              />-->
<!--              <img v-if="scope.row.appTag == 10 && count > 0"-->
<!--                @click="del(scope.$index, scope.row)"-->
<!--                class="edit-img"-->
<!--                src="../../assets/image/trash.png"-->
<!--              />-->
          </template>
        </el-table-column>

      </el-table>


      <div style="margin-top: 60px;margin-left: 150px;">
        <el-button type="primary" @click="checkSubmitData()" center>保存</el-button>
        <!--<el-button @click="cancle()">取 消</el-button>-->
      </div>

    </div>
  </div>
</template>

<script>
let vm = null;
import { openLoading, closeLoading } from "../../utils/utils";
import BreadCrumb from "@/components/breadcrumb.vue";
import { getRangeList,updateRangeStatus, getCircleSettingList, saveCircleSetting, getActivityList, delActivity} from "../../utils/yqrange/yqrangeApi";
import { isEmptyUtils } from "../../utils/index";

export default {
  components: {
    BreadCrumb
  },
  data(){
    return{
      curmbFirst: '云鹊专区',
      showAllFlag: false,
      showNewFlag: false,
      searchForm: {
        name: '',
        createdTime: '',
        // endTime: '',
        userType: "", // 用户标识 1：内部用户 2：外部用户,
        status: "",
        pageNo: 1,
        pageSize: 10,
      },
      totalRows: 0,
      tableData: [],
      dialogSettingVisible: false,
      settingForm:{
        circleId: null,
        settingData: [],
        activityList:[]
      },
      tempList: [],
      count: 0,
    }
  },
  created() {
    vm = this;
    this.circleId = this.$route.query.id;
    this.setting();
    this.initActivityList();
  },
  methods: {

    // 应用配置
    setting(){
      let params = {
        circleId: this.circleId
        // circleId: 194
      }

      getCircleSettingList(params).then((res) => {
        closeLoading(this);
        if(res.code == "000000") {
          this.settingForm.settingData = res.data;
          if(this.settingForm.settingData != null
            && this.settingForm.settingData.length > 0){
            for (let i = 0; i<this.settingForm.settingData.length; i++){
              // 自定义积木
              if(this.settingForm.settingData[i].appTag == 10){
                this.count ++;
                if(this.settingForm.settingData[i].appUrl != ""){
                  this.settingForm.settingData[i].appUrl = parseInt(this.settingForm.settingData[i].appUrl);
                }
              }
            }
            this.count --;
            let tempList = this.settingForm.settingData.filter(function (item) {
              return item.appTag == 10;
            });
            if(tempList.length == 0){
              let row = {
                appName: "",
                appTag: 10,
                appType: "自定义H5积木页",
                appUrl: "",
                ecoAppParams: [],
                id: "",
                seqNo: this.settingForm.settingData.length + 1,
                showOff: 0,
              }
              this.settingForm.settingData.push(row);
            }
          }
        } else {
          this.settingForm.settingData = [];
        }
      }).catch((error) => {
        this.$message.error("请重试");
      })

    },

    checkSubmitData() {
      for(let i=0; i<this.settingForm.settingData.length; i++) {
        if (this.settingForm.settingData[i].showOff == 1 && isEmptyUtils(this.settingForm.settingData[i].appName)) {
          this.$message.error("重命名输入框中的值不可为空，请检查");
          return;
        }
        if (isEmptyUtils(this.settingForm.settingData[i].seqNo)) {
          this.$message.error("序号不可为空，请检查");
          return;
        }
        if (this.settingForm.settingData[i].showOff == 1
          && this.settingForm.settingData[i].appTag == 10
          && isEmptyUtils(this.settingForm.settingData[i].appUrl)) {
          this.$message.error("请选择积木页");
          return;
        }
        const r = /^\+?[1-9][0-9]*$/; // 正整数
        // 如果判断不符合正则，则不是正整数不能提交
        if (!r.test(this.settingForm.settingData[i].seqNo)) {
          this.$message.error("序号应为正整数，请检查");
          return;
        }
        if (this.settingForm.settingData[i].seqNo < 1 || this.settingForm.settingData[i].seqNo > 10) {
          this.$message.error('请输入 1~10 的正整数');
          return;
        }
        if (this.settingForm.settingData[i].seqNo > this.settingForm.settingData.length) {
          this.$message.error("序号必须从1开始顺序排列，不能有跳序情况，请检查");
          return;
        }
        for(let j=0; j<this.settingForm.settingData.length; j++) {
          if (i == j) {
            continue;
          }
          if (this.settingForm.settingData[i].seqNo == this.settingForm.settingData[j].seqNo) {
            this.$message.error("序号不可重复，请检查");
            return;
          }
        }
      }
      this.save();
    },

    // 保存
    save(){
      let params = {
        apps: this.settingForm.settingData,
        circleId: this.circleId
      }

      saveCircleSetting(params).then((res) => {
        closeLoading(this);
        if(res.code == "000000") {
          this.$message.success("保存成功！");
          // this.$router.go(-1);
          this.setting();
        }
      }).catch((error) => {
      this.$message.error("请重试");
      })
    },

    cancle(){
      this.$router.go(-1);
    },

    BlurText(e) {
      console.log("BlurText() : e = " + e.target.value)
      let b = new RegExp("^[1-9][0-9]*$").test(e.target.value)
      if (e.target.value >= 10) {
        b = false
      }
      if (!b) {
        this.$message.warning('请输入 1~10 的正整数')
        e.target.value = ''
      }
    },

    // 应用配置
    initActivityList(){
      let params = {
        // circleId: this.circleId
        id: "",
        title: "",
        publishFlag: 5,
        createdTime: "",
        pageNo: 1,
        pageSize: 20000

      }
      getActivityList(params).then((res) => {
        closeLoading(this);
        if(res.code == "000000") {
          this.settingForm.activityList = res.data.templateList;
        } else {
          this.settingForm.activityList = [];
        }
      }).catch((error) => {
        this.$message.error("请重试");
      })

    },

    indexMethod(index){
      this.index = index;
    },
    add(index){
      if(this.settingForm.settingData != null && this.settingForm.settingData.length > 0 ){
        this.tempList = this.settingForm.settingData.filter(function (item) {
          return item.appTag == 10;
        });
        if(this.tempList.length > 0){
          this.row = {
            appName: "",
            appTag: 10,
            appType: this.tempList[0].appType,
            appUrl: "",
            ecoAppParams: [],
            id: "",
            seqNo: index+2,
            showOff: 0,
          }
          this.count ++;
          this.settingForm.settingData.push(this.row);
        }

      }


    },
    del(index, row){
      let params = {
        circleId: this.circleId,
        id: row.id
      }

      vm.$confirm(`确定删除“${row.appName}”吗？`, "", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
        // customClass: 'range-make-box',
      })
        .then(() => {

          if (params.id == "") {
            vm.$message({
              type: "success",
              message: "删除成功"
            });
            vm.count--;
            vm.settingForm.settingData.splice(index, 1);
          } else {
            //  confirm
            delActivity(params).then(res => {
              if (res.code == "000000") {
                vm.$message({
                  type: "success",
                  message: "删除成功"
                });
                vm.count--;
                vm.settingForm.settingData.splice(index, 1);
              } else {
                vm.$message({
                  type: "warning",
                  message: res.message
                });
              }
            });
          }
        })
        .catch(() => {});

    },
    activityColor({row, column, rowIndex, columnIndex}){
      return "activity-color";
    }

  },
}
</script>
<style lang="scss">
  .yqrange-index-wrapper{
    .yqrange-index-content{
      background: #fff;
      padding: 10px;
      .header-title{
        padding: 10px 12px;
        font-size: 12px;
        color: #449284;
        border-bottom: 1px solid #efefef;
      }
    }
    .el-button--text{
      color: #449284;
      font-size: 14px;
      &::after{
        content: '';
        position: relative;
        height: 14px;
        /*border-right: 1px solid #EBEEF5;*/
        border-right: 1px solid #aaaaaa;
        padding-right: 10px;
      }
      &:last-of-type{
        &::after{
          content: '';
          position: relative;
          width: 1px;
          height: 14px;
          border-right: none;
        }
      }
    }
  }
  /*.range-make-box{*/
    /*.el-message-box__btns{*/
      /*margin-top: 30px;*/
    /*}*/
  /*}*/
  // 去掉表格单元格边框
.customer-table th{
    border:none;
  }
.customer-table td,.customer-table th.is-leaf {
  border:none;
}
// 表格最外边框
.el-table--border, .el-table--group{
  border: none;
}
// 头部边框
.customer-table thead tr th.is-leaf{
  width: 0;
}
.customer-table thead tr th:nth-last-of-type(2){
  width: 0;
}
// 表格最外层边框-底部边框
.el-table--border::after, .el-table--group::after{
  width: 0;
}
.customer-table::before{
  width: 0;
}
.customer-table .el-table__fixed-right::before,.el-table__fixed::before{
  width: 0;
}
// 表格有滚动时表格头边框
.el-table--border th.gutter:last-of-type {
    width: 0;
}
  .el-select-dropdown {
    width: 300px;
  }
.el-table .activity-color {
    color: #EC808D;
  }
</style>
