<template>
  <div class="yqrange-index-wrapper">
    <bread-crumb :curmbFirst="curmbFirst"></bread-crumb>
    <div class="yqrange-index-content screenSet">
      <el-tabs v-model="activeName" @tab-click="tabChangeHandler">
        <el-tab-pane label="云鹊专区" name="first">
      <el-form ref="searchForm" :model="searchForm" label-width="75px" label-suffix=":" :inline="true">
        <el-row :gutter="30" type="flex" style="margin-top: 10px">
          <el-col :span="8">
            <el-form-item label="圈子名称">
              <el-input v-model="searchForm.name" size="small" placeholder="请输入圈子名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="创建时间">
              <el-date-picker
                  v-model="searchForm.createdTime"
                  size="small"
                  type="date"
                  placeholder="请选择创建时间"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7" style="text-align: right">
            <el-button type="primary" size="small" @click="search">搜索</el-button>
            <el-button type="default" size="small" @click="resetForm" style="margin-left:0;">取消搜索</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right">
            <el-button type="primary" size="small" @click="createRange" v-if="showNewFlag">新建小圈</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="tableData" class="item-table" style="width: 100%;margin-top: 10px;">
        <el-table-column prop="id" label="圈子ID" min-width="100" align="center"></el-table-column>
        <el-table-column prop="createdTime" label="创建时间" min-width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createdTime | liveDateFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="圈子名称" min-width="100" align="center"></el-table-column>
        <el-table-column prop="numberOfPeople" label="圈子人数" min-width="100" align="center"></el-table-column>
        <el-table-column prop="dynamicFlag" label="内容发布权限" min-width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.dynamicFlag | dynamicFlagStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="圈子状态" min-width="100" align="center">
          <template slot-scope="scope">
            <!--<span>{{ scope.row.status | rangeStatus }}</span>-->
            <span v-if="scope.row.status == 10 || scope.row.status == 40" style="color: #FAAD14">{{ scope.row.status | rangeStatus }}</span>
            <span v-if="scope.row.status == 30" style="color: #1890FF">{{ scope.row.status | rangeStatus }}</span>
            <span v-if="scope.row.status == 0 || scope.row.status == 50" style="color: #c7c8c9">{{ scope.row.status | rangeStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="370" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.status != 50">
              <el-button @click="publishRange(scope.row)" v-if="scope.row.status != 30 && scope.row.status != 0" type="text" size="small">上线</el-button>
              <el-button @click="unPublishRange(scope.row)" v-if="scope.row.status == 30 && scope.row.status != 0" type="text" size="small">下线</el-button>
              <!--<el-button @click="liveManage(scope.row)" type="text" size="small" v-if="scope.row.status != 0">直播管理</el-button>-->
              <!--<el-button @click="roleManage(scope.row)" type="text" size="small" v-if="scope.row.status != 0">成员管理</el-button>-->
              <el-button @click="editRange(scope.row)" type="text" size="small">编辑</el-button>
              <el-button @click="deleteRange(scope.row)" type="text" size="small" v-if="showAllFlag && scope.row.status != 0">解散圈子</el-button>
              <!--<el-button @click="setting(scope.row)" type="text" size="small" v-if="scope.row.status != 0 && showNewFlag">应用配置</el-button>-->
              <el-button @click="rangeManage(scope.row)" type="text" size="small" v-if="scope.row.status != 0">管理</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleNumChange"
            :current-page="searchForm.pageNo"
            :page-sizes="[10, 30, 50, 100, 200]"
            :page-size="searchForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalRows"
        ></el-pagination>
      </div>
      <el-dialog
        title="应用配置"
        :visible.sync="dialogSettingVisible"
        width="500px"
        :close-on-click-modal="false"
        @close="handleSettingClose"
        center>

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


          <div v-for="(item, index) in settingForm.settingData" :key="index">

          <el-form-item :label="item.appTagName">
            <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-form-item>


          </div>

        </el-form>


        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button type="primary" @click="save" center>保存</el-button>
        </div>


      </el-dialog>

          <el-dialog
            title=""
            :show-close="false"
            :visible.sync="confirmVisible"
            :close-on-click-modal="false"
            width="600px"
            center
          >
            <p style="text-align: center;">{{confirmMessage}}</p>
            <span slot="footer" class="dialog-footer">
        <!--<el-button @click="confirmDelete">删 除</el-button>-->
        <el-button type="primary" @click="hideConfirm">确定</el-button>
      </span>
          </el-dialog>

        </el-tab-pane>

        <el-tab-pane label="审核列表" name="second" v-if="showApplyFlag">
          <range-apply></range-apply>
        </el-tab-pane>

      </el-tabs>

    </div>


  </div>


</template>
<script>
  import { openLoading, closeLoading } from "../../utils/utils";
  import BreadCrumb from "@/components/breadcrumb.vue";
  import { getRangeList,updateRangeStatus, getCircleSettingList, saveCircleSetting} from "../../utils/yqrange/yqrangeApi";
  import ElTabPane from "element-ui/packages/tabs/src/tab-pane";
  import RangeApply from "./range-apply";
export default {
  components: {
    RangeApply,
    ElTabPane,
    BreadCrumb
  },
  data(){
    return{
      curmbFirst: '云鹊专区',
      activeName: 'first',
      showAllFlag: false,
      showNewFlag: false,
      showApplyFlag: false,
      searchForm: {
        name: '',
        createdTime: '',
        // endTime: '',
        userType: "", // 用户标识 1：内部用户 2：外部用户,
        status: "",
        pageNo: 1,
        pageSize: 10,
      },
      totalRows: 0,
      tableData: [],
      dialogSettingVisible: false,
      settingForm:{
        circleId: null,
        settingData: []
      },
      idType: "",
      confirmMessage: "",
      confirmVisible: false,
    }
  },
  created() {
    this.initPrivilege();
    this.search();
  },
  methods: {

    tabChangeHandler(tab) {},

    initPrivilege(){
      this.idType = localStorage.getItem('storageIdType');
      // if(idType == null || idType == ""){
      //   idType = 2;
      //   localStorage.setItem('storageIdType', idType);
      // }
      this.searchForm.userType = this.idType;

      // 内部用户:运营人员
      if(this.idType == "1"){
        this.showAllFlag = true;
        this.showNewFlag = true;
        this.showApplyFlag = true;
      }
      // 外部用户
      else if(this.idType == "2"){
        this.showAllFlag = false;
        setTimeout(() => {
           this.getUserAuth();
        },800)
      }

    },
    // 外部用户权限
    getUserAuth(){

      let highMainManager = localStorage.getItem('highMainManager');
      let mainManager = localStorage.getItem('mainManager');
      let manager = localStorage.getItem('manager');
      let ordinary = localStorage.getItem('ordinary');
      let createCircle = localStorage.getItem('createCircle');

      // 新建小圈权限
      if(createCircle == "1"){
        this.showNewFlag = true;
      }
      else {
        this.showNewFlag = false;
      }

      // 是否显示审核列表
      if(highMainManager == "1" || mainManager == "1"){
        // this.showNewFlag = true;
        this.showApplyFlag = true;
      }
      else if(manager == "1"){
        // this.showNewFlag = false;
        this.showApplyFlag = true;
      }
      else if(ordinary == "1"){
        this.showApplyFlag = false;
      }

      // localStorage.setItem('ordinary', vm.setStoreData(ordinary))

    },

    // 搜索
    search(){
      this.searchForm.pageNo = 1;
      this.searchList();
    },

    searchList() {
      openLoading(this);
      let params = this.searchForm;

      console.log('查询圈子')
      getRangeList(params).then((res) => {
        closeLoading(this);
        if(res.code == "000000") {
          this.tableData = res.data.circleList;
          this.totalRows = res.data.count;
        } else {
          this.tableData = [];
        }
      }).catch((error) => {
        // this.$message({
        //   message: error,
        //   type: 'error'
        // });
        this.$message.error("请重试");
      })
    },

    resetForm() {
      this.searchForm.name = "";
      this.searchForm.createdTime = "";
      console.log('重置')
      this.search();
    },
    //新建小圈
    createRange() {
      let enterType = 1;//1:add 2 edit
      this.$router.push({
        path: `/create-range?enterType=${enterType}`
      })
    },
    //上线
    publishRange(row) {
      this.$confirm(`上线后圈子成员将收到入圈消息提醒（每天最多提醒一次），确定上线“${row.name}”吗？`, '', {
        confirmButtonText: '上线',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'range-make-box',
      }).then(() => {
        //  confirm
        this.updateStatus(row.id, "30");
      }).catch(() => {
        //  cancel
        // this.$message.error("上线失败");
      });
    },
    //下线
    unPublishRange(row) {
      this.$confirm(`确定下线“${row.name}”吗？`, '', {
        confirmButtonText: '下线',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'range-make-box',
      }).then(() => {
        this.updateStatus(row.id, "40");
        //  confirm
      }).catch(() => {
        //  cancel

      });
    },
    // 更新圈子状态（上线，下线）
    updateStatus(id, status){
      let params = {"id": id, "status": status};
      updateRangeStatus(params).then((res) => {
        closeLoading(this);
        if(res.code == "000000") {
          if(status == "40"){
            this.$message.success("下线成功");
          } else if(status == "30") {
            this.$message.success("上线成功");
          }else if(status == "50") {
            this.$message.success("解散成功");
          }
          this.searchList();
        }
        else if(res.code == "224027") {

          this.confirmMessage = `圈子已被加入广场中，请先至广场管理移除该圈子后再操作`;
          this.confirmVisible = true;
        }
        else {
          if(status == "40"){
            this.$message.error("下线失败，请重试");
          } else if(status == "30") {
            this.$message.error("上线失败，请重试");
          }else if(status == "50") {
            this.$message.error("解散失败，请重试");
          }


        }
      }).catch((error) => {
        // this.$message({
        //   message: error,
        //   type: 'error'
        // });
        if(status == "40"){
          this.$message.error("下线失败，请重试");
        } else if(status == "30") {
          this.$message.error("上线失败，请重试");
        }else if(status == "50") {
          this.$message.error("解散失败，请重试");
        }
      })


    },

    hideConfirm(){
      this.confirmVisible = false;
    },

    rangeManage(row) {
      this.$router.push({
        path: '/range-manage',
        query: {
          id: row.id,
          name: row.name,
          activeName: 'first',
          roleType: row.roleId,
        }
      })
    },

    //直播管理
    liveManage(row) {
      this.$router.push({
        path: '/live-manage?id=' + row.id,
      })
    },
    //成员管理
    roleManage(row) {
      this.$router.push({
        path: '/role-manage?id=' + row.id,
      })
    },
    //编辑
    editRange(row) {
      let enterType = 2;//1:add 2 edit
      this.$router.push({
        path: `/create-range?enterType`,
        query:{
          id:row.id,
          enterType:enterType,
          roleType: row.roleId
        }
      })
    },
    //解散圈子
    deleteRange(row) {
      this.$confirm(`解散后圈子内的动态/直播等内容将不会保存`, `确定解散“${row.name}”吗？`, {
        confirmButtonText: '解散',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'range-make-box',
      }).then(() => {
        this.updateStatus(row.id, "50");
        //  confirm
      }).catch(() => {
        //  cancel
      });
    },

    // 应用配置
    setting(row){
      this.dialogSettingVisible = true;

      this.settingForm.circleId = row.id;
      let params = {
        circleId: this.settingForm.circleId
        // circleId: 22
      }

      getCircleSettingList(params).then((res) => {
        closeLoading(this);
        if(res.code == "000000") {
          this.settingForm.settingData = res.data;

        } else {
          this.settingForm.settingData = [];
        }
        if(this.settingForm.settingData == [] || this.settingForm.settingData.length == 0){

          this.settingForm.settingData = [{
            appTag: 1,
            showOff: 1
          },
            {
              appTag: 2,
              showOff: 1
            },
            {
              appTag: 3,
              showOff: 1
            },
            {
              appTag: 4,
              showOff: 1
            }];
        }

        for(let i = 0; i < this.settingForm.settingData.length; i++){
          if(this.settingForm.settingData[i].appTag == 1){
            this.settingForm.settingData[i].appTagName = "教培"
          }
          else if(this.settingForm.settingData[i].appTag == 2){
            this.settingForm.settingData[i].appTagName = "直播"
          }
          else if(this.settingForm.settingData[i].appTag == 3){
            this.settingForm.settingData[i].appTagName = "继教课程"
          }
          else if(this.settingForm.settingData[i].appTag == 4){
            this.settingForm.settingData[i].appTagName = "职称培训"
          }
        }


      }).catch((error) => {
        this.$message.error("请重试");
      })

    },

    // 关闭
    handleSettingClose(){
      this.dialogSettingVisible = false;
    },

    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.search();
    },
    handleNumChange(val) {
      this.searchForm.pageNo = val;
      this.searchList();
    },
    // 保存
    save(){

      let params = {
        apps: this.settingForm.settingData,
        circleId: this.settingForm.circleId
      }


      saveCircleSetting(params).then((res) => {
        closeLoading(this);
        if(res.code == "000000") {
          this.$message.success("保存成功！");

          this.dialogSettingVisible = false;
        }
    }).catch((error) => {
    this.$message.error("请重试");
    })

    },
    getRangeNotice(){
      this.$router.push({
        path: '/range-notice'
      })
    }

  },
}
</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;*/
    /*}*/
  /*}*/
</style>
