<template>
  <div class="customer-wrap">
    <v-tour name="custListTour" :steps="steps" :options="tourOptions"></v-tour>
    <div>
      <section class="search-box" v-if="showSearch">
        <section class="search-cnt">
          <el-input v-model="searchQuery" placeholder="输入分群名称" clearable @clear="handSearch"
            @keyup.enter.native="handSearch">
          </el-input>
          <section class="search-btn" icon="el-icon-search" @click="handSearch">
            <i class="el-icon-search"></i>
          </section>
        </section>
      </section>
      <section class="main-wrap">
        <section class="operate-cnt">
          <el-radio-group v-model="selectedTab" @change="handleTabChange" class="plain-raido-btn" size="medium">
            <el-radio-button label="我创建的" :disabled="radiosButonIsDisableFromMe">我创建的</el-radio-button>
            <el-radio-button label="推荐给我的" disabled>推荐给我的</el-radio-button>
          </el-radio-group>
          <div style="display: flex; justify-content: space-between">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"
              style="margin-right: 25px; margin-top: 15px"></right-toolbar>
            <el-button type="primary" :disabled="selection.length === 0" icon="el-icon-plus"
              @click="startAddTask">批量添加任务</el-button>
            <!-- <el-button type="primary" icon="el-icon-plus" @click="showCreateDialog = true">创建分群</el-button> -->
            <el-button type="primary" icon="el-icon-plus" @click="handleRuleCreation">规则创建</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="handleImport">导入创建</el-button>
          </div>
        </section>
        <section class="table-wrap">
          <el-table id="selectTable" ref="selectTable" :data="groupTable" style="width: 100%" @selection-change="handleSelectRow" max-height="630">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="groupName" label="分群名称" sortable v-if="columns[0].visible"
              width="180px"></el-table-column>
            <el-table-column prop="custType" label="客户类型" sortable v-if="columns[1].visible">
              <template slot-scope="scope">
                <span v-if="scope.row.custType == 0">个人</span>
                <span v-if="scope.row.custType == 1">商户</span>
                <span v-if="scope.row.custType == 2">企业</span>
              </template>
            </el-table-column>
            <el-table-column prop="customerNum" label="人数" sortable v-if="columns[2].visible"></el-table-column>
            <el-table-column prop="" label="创建方式" sortable v-if="columns[3].visible">
              <template slot-scope="scope">
                <span v-if="scope.row.createType == '0'">导入创建</span>
                <span v-if="scope.row.createType == '1'">规则创建</span>
                <span v-if="scope.row.createType == '2'">锚点分群</span>
              </template>
            </el-table-column>
            <el-table-column prop="createBy" label="创建者" sortable v-if="columns[4].visible"></el-table-column>
            <el-table-column prop="" label="更新方法" sortable v-if="columns[5].visible">
              <template slot-scope="scope">
                <span v-if="scope.row.updateType == '0'">自动更新</span>
                <span v-if="scope.row.updateType == '1'">手动更新</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" sortable v-if="columns[6].visible"></el-table-column>
            <el-table-column sortable prop="updateTime" label="最近更新时间" v-if="columns[7].visible"
              width="180px"></el-table-column>
            <el-table-column prop="operate" label="操作" align="center" width="250px">
              <template #header>
                <div class="label-box">
                  操作
                  <el-tooltip placement="top" trigger="hover" content="只能删除由自己创建的客群" width="200">
                    <span class="quesiton"><i class="el-icon-question"></i></span>
                  </el-tooltip>
                </div>
              </template>
              <template slot-scope="scope">
                <!-- <el-button type="text"
                  @click="importCustomer">
                  导入
                </el-button> -->
                <el-button type="text" @click="
                  handleCustDetail(
                    scope.row.groupId,
                    scope.row.groupName,
                    scope.row.campaignId,
                    scope.row.groupType,
                    '0',
                    scope.row.distributeType,
                    scope.row.custType,
                    scope.row,
                    scope.row.createRole
                  )
                " :disabled="scope.row.checkType != '1'">查看</el-button>
                <!-- <a href="#" @click.prevent="importIn">导入</a> -->
                <el-button type="text" @click="handleGroupCustExport(scope.row.groupId, scope.row.groupName)"
                  :disabled="scope.row.checkType != '1'">导出</el-button>
                <!-- <a href="#" @click.prevent="recommend">推荐</a> -->
                <!-- <el-button 
                  type="text" 
                  :disabled="
                    !scope.row.createBy.includes(userName)
                " @click="
                  handlePushGroupCustomer(
                    scope.row.groupName,
                    scope.row.groupId,
                    scope.row.campaignId,
                    scope.row.custType
                  )
                  ">推送</el-button> -->
                <el-button type="text" :disabled="!roles.includes(scope.row.createRole)"
                  @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页区域 -->
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="->,total,prev,pager,next,sizes" :total="total"
            :current-page="pageNum"></el-pagination>
        </section>
      </section>

    </div>
    <div class="dialog-container">
      <el-dialog :visible.sync="showCreateDialog" title="怎样创建分群" width="38%" class="dialog-header">
        <div class="dialog-content">
          <div class="group-section" @click="handleRuleCreation">
            <!-- <i class="el-icon-edit"></i> -->
            <svg-icon icon-class="rule" class="el-icon-edit-rule" />
            <div class="group-text">
              <h3>规则创建</h3>
              <p>
                使用客户属性及行为数据，筛选出符合条件的客户。如：将“我行有存款且无贷款”的客户，划分为“我行存款无贷”客户群
              </p>
            </div>
          </div>
          <div class="group-section" @click="handleImport">
            <svg-icon icon-class="import" class="el-icon-add-import" />
            <div class="group-text">
              <h3>导入创建</h3>
              <p>下载模板并填写数据，并将导入结果保存为客户分群</p>
            </div>
          </div>
          <!-- <el-button>规则创建</el-button>
          <el-button type="primary" @click="handleImport">导入创建</el-button> -->
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="
            () => {
              showCreateDialog = false;
              this.campaignId = null;
              this.defaultListData = []
              this.getList();
            }
          ">取消</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="dialog-container">
      <el-dialog :visible.sync="importVisible" title="" width="25%" class="dialog-header" center>
        <div class="dialog-content">
          <div class="group-text err-text">
            <p>
              {{ warningStr }}
            </p>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleImportCancle">取 消</el-button>
          <el-button type="primary" @click="handleErrExport">
            导出
          </el-button>
        </span>
      </el-dialog>
    </div>
    <CustomerImport :drawerVisible="drawerVisible" />
    <div class="dialog-container" id="taskDialogId">
      <el-dialog :visible.sync="showTaskDialog" title="是否添加到已有任务?" width="25%" class="dialog-header"
        @close="closeTaskDialog">
        <div class="child-main">
          <el-form :model="formObj" :rules="formRules" ref="formObj" class="my-form">
            <el-form-item label="" prop="task">
              <el-select style="width: 300px" v-model="formObj.task" placeholder="请选择任务" filterable>
                <el-option v-for="item in taskOptions" :key="item.value" :label="item.label" :value="item.value">{{
                  item.label }}</el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="dialog-footer">
            <el-button type="primary" @click="onSubmit">确认</el-button>
            <el-button type="primary" @click="goToCreateTask" class="handle-btn">创建新任务</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import CustomRule from './components/custom-rule'
import CustomerImport from './components/customer-import.vue'
import { groupList, exportData, DeleteGroupByGroupId, getCurrentExistTask, addToCurrentExistTask } from "@/api/system/grouplist";
import { isHead, campaignDetail, findCustListByGroupId } from "@/api/system/findCustByGroupId.js";
import { campaignAdd } from "@/api/system/campaign.js";
import { Message } from "element-ui";
import { mapGetters } from 'vuex'
import { isFirstLogin } from "@/api/login";
import { uid } from '@/utils'
export default {
  components: { CustomRule, CustomerImport },
  props: [],
  data() {
    return {
      steps: [
        {
          target: '#nestsegmentation',
          content: '<div style="font-size:20px;line-height:25px">首先前往客群自定义网格菜单页</div><br><span></span>',
          overlay: true,
          params: {
            placement: 'bottom',
            highlight: true,
            mask: true
          }
        },
        {
          target: '#selectTable',
          content: '<div style="font-size:20px;line-height:25px">然后选取一个或多个同类型客群</div><br><span></span>',
          overlay: true,
          params: {
            placement: 'top',
            highlight: true,
            mask: true
          },

        },
        {
          target: '#taskDialogId .el-dialog',
          content: '<div style="font-size:20px;line-height:25px">然后选取一个或多个同类型客群，可以选择添加已有任务，创建新任务，以下演示创建新任务</div><br><span></span>',
          overlay: true,
          params: {
            placement: 'right',
            highlight: true,
            mask: true
          },
          before: () => {
            this.showTaskDialog = true
          }
        },
        {
          target: '',
          content: '',
          overlay: true,
          params: {
            placement: 'auto',
            highlight: true,
            mask: true
          },
          before: () => {
            return this.$router.push({ path: '/taskManage/taskCreation' }).then(() => {
              return new Promise(resolve => {
                const checkElement = () => {
                  sessionStorage.setItem('isSegTour', 1)
                  if (document.querySelector('#fillInformationOne')) {
                    resolve()
                  } else {
                    setTimeout(checkElement, 100)
                  }
                }
                checkElement()
              })
            })
          }
        },
      ],
      tourOptions: {
        highlight: true,
        labels: {
          buttonSkip: '跳过',
          buttonPrevious: '上一步',
          buttonNext: '下一步',
          buttonStop: '完成'
        },
        enabledButtons: {
          buttonSkip: true,
          buttonPrevious: true,
          buttonNext: true,
          buttonStop: true,
        },
        useKeyboardNavigation: true,
        startTime: 0,
        stopOnTargetNotFound: true,
        debug: false,
      },
      isLoading: false,
      isCustomerShow: false,
      ruleArr: [
        {
          label: '按管户归属',
          value: '1',
          disabled: true
        },
        {
          label: '按地址归属',
          value: '2'
        },
        {
          label: '手动指定',
          value: '0'
        }
      ],
      isShowDistribute: false,
      custType: '',
      options: [],
      selectedValues: [],
      distributeList: [],
      selectOptions: [

      ],
      pageNum: 1,
      isPushBtn: false,
      columns: [
        { key: 0, label: `分群名称`, visible: true },
        { key: 1, label: `客户类型`, visible: true },
        { key: 2, label: `人数`, visible: true },
        { key: 3, label: `创建方式`, visible: true },
        { key: 4, label: `创建者`, visible: true },
        { key: 5, label: `更新方法`, visible: true },
        { key: 6, label: `状态`, visible: true },
        { key: 7, label: `最近更新时间`, visible: true },
      ],
      pushOpen: false,
      isHeader: false,
      pushroles: {
        groupName: [
          { required: true, message: "分群名称不能为空" },
          {
            min: 2,
            max: 20,
            message: "分群名称长度必须介于 2 和 20 之间",
          },
        ],
        campaignName: [
          { required: true, message: "活动名称不能为空" },
          {
            min: 2,
            max: 20,
            message: "活动名称长度必须介于 2 和 20 之间",
          },
        ],
        campaignType: [{ required: true, message: "请选择活动类型" }],
        campaignDegree: [{ required: true, message: "请选择紧急程度" }],
        claimType: [{ required: true, message: "请选择认领类型" }],
        dateRange: [{ required: true, message: "请选择活动时间" }],
        claimdateRange: [{ required: true, message: "请选择认领时间" }],
        executer: [{ required: true, message: "请选择执行人" }],
        // distributeType: [
        //   { required: , message: "请选择分配规则", trigger: "blur" },
        // ],
      },
      pushform: {
        groupName: "",
        claimType: "",
        campaignDegree: "",
        campaignType: "",
        campaignName: "",
        executer: {},
        distributeType: {},
        claimdateRange: [],
        dateRange: [],
        distributeType: '',
        distributeType2: '',
        distributeType3: ''
      },
      pushOpen: false,
      ruleMap: {},
      pushTitle: "创建活动",
      radiosButonIsDisableFromMe: false,
      radiosButonIsDisableToMe: false,
      userType: "0",
      showmap: false,
      total: 0,
      pageSize: 10,
      currentPage: 1,
      isCreatePag: false,
      groupFlag: "1",
      groupTable: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,

      selectedTab: "我创建的",
      searchQuery: "",
      showCreateDialog: false,
      selectedCreateType: "",
      isCreatePage: false,
      tableData: [],
      groupId: "",
      createRole: "",
      campaignId: "",
      ispushformread: false,
      pushformDetail: {},
      num: 1,
      defaultListData: [],
      pickOption: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      importVisible: false,
      drawerVisible: false,
      selection: [],
      showTaskDialog: false,
      taskOptions: [
        // {lable:'任务1',value:'1'},
        // {lable:'任务2',value:'2'},
        // {lable:'任务3',value:'3'},
      ],
      formObj: {
        task: ''
      },
      formRules: {
        task: [
          {
            required: true,
            message: '任务不能为空',
            trigger: 'blur'
          },
        ]
      },
      curGroupId: '',
      curGroupName: '',
      warningStr: '',
    };
  },
  computed: {
    ...mapGetters(['roles', 'userName', 'groupErr']),
    isSegTour() {
      return sessionStorage.getItem('isSegTour')
    },
    //对公
    isPublic() {
      return this.roles.includes('headPublic')
    },
    //对私
    isPrivate() {
      return this.roles.includes('headPrivate')
    },
    filteredTableData() {
      if (this.searchQuery) {
        return this.groupTable.filter((item) =>
          item.groupName.includes(this.searchQuery)
        );
      }
      return this.groupTable;
    },
    configRules() {
      const newArr = []
      if (this.custType == '个人') {
        newArr.push({
          ruleTitle: '个人客户分配规则配置',
          ruleName: 'personal',
          key: uid()
        })
        this.ruleMap.personal = [

        ]
      }

      if (this.custType == '商户') {
        newArr.push({
          ruleTitle: '商户客户分配规则配置',
          ruleName: 'merchant',
          key: uid()
        })
        this.ruleMap.merchant = [

        ]
      }

      if (this.custType == '企业') {
        newArr.push({
          ruleTitle: '企业客户分配规则配置',
          ruleName: 'company',
          key: uid()
        })
        this.ruleMap.company = [

        ]
      }
      return newArr
    }
  },
  created() {
    // this.$router.go(0)
    this.isUserType();
    this.getList();
  },
  mounted() {
    //初始化表格数据
    this.handleTabChange();
    console.log(this.groupErr)
    if (this.groupErr.warningStr) {
      this.importVisible = true;
      this.warningStr = this.groupErr.warningStr;
      this.curGroupId = this.groupErr.groupId;
      this.curGroupName = this.groupErr.groupName;
    }
    this.initIsFirstLogin()
    // this.$store.commit("SET_GROUP_CUSTOMS", []);
  },

  methods: {
    initIsFirstLogin() {
      const params = {
        username: this.userName
      }
      isFirstLogin(params).then(res => {
        if (res.code == 200) {
          // 用户首次登陆
          // 用户已有登录记录
          if (res.msg == '用户首次登陆') {
            setTimeout(() => {
              this.startTour()
            }, 1000)
          } else {
            if (this.isSegTour == '0') {
              setTimeout(() => {
                this.startTour()
              }, 1000)
            }
          }
        }
      })
    },
    startTour() {
      this.$tours['custListTour'].start()
    },
    // 获取当前已有任务
    searchCurrentExistTask(params) {
      getCurrentExistTask(params).then(res => {
        if (res.code == 200) {
          this.taskOptions = res.data.map(item => {
            return {
              label: item.campaignName,
              value: item.campaignId,
            }
          });
        }
      })
    },
    // 添加客群到已选任务
    addGroupsToExistTask(params) {
      addToCurrentExistTask(params).then(res => {
        if (res.code == 200) {
          this.closeTaskDialog();
          Message.success('添加成功');
        }
      })
    },
    changeClaimdate(value) {

      if (this.pushform.dateRange.length == 0) {
        Message.warning('请先选择活动时间')
        this.pushform.claimdateRange = []
      } else {
        console.log(this.pushform.dateRange, 'this.pushform.dateRange')
        let hdTimeStart = this.pushform.dateRange[0]
        let hdTimeEnd = this.pushform.dateRange[1]
      }
    },
    getRuleArr(obj) {
      this.ruleMap[obj.ruleName] = obj.arr
      console.log(this.ruleMap, '===============>>')
    },
    handleMessage() {
      Message.warning('禁止删除')
    },
    handleSelectChange(value, index) {
      this.selectedValues[index] = value;
    },
    addSelect() {

      this.distributeList.push({
        priority: this.num++,
        distributeType: ''

      })
      this.distributeList.forEach(item => {
        this.selectOptions.filter(el => el.value != item.distributeType)
      })
      this.distributeList.forEach((item, priority) => {
        item.priority = priority + 1;
        //如果是第一优先级,任何时候都是三种

      })
    },
    removeSelect(index, item) {
      console.log(item, 'itemitem')
      // if(item.distributeType == 1){
      //   this.selectOptions.push({
      //   value:2,label:`按地址归属2222`
      // },{value:1,label:`按客户归属11111`})
      // }else if(item.distributeType == 2){
      //   this.selectOptions.push({
      //   value:1,label:`按客户归属11111`
      // },{
      //   value:2,label:`按地址归属2222`
      // })
      // }
      // console.log(this.selectOptions,'this.selectOptions')

      this.distributeList.splice(item.priority - 1, 1)
      //  console.log(this.selectOptions,'this.selectOptions')
      this.distributeList.forEach((item, priority) => {
        item.priority = priority + 1;
        //如果是第一优先级,任何时候都是三种

      })
    },
    handleChange(val) {
      this.selectOptions = this.selectOptions.filter(item => item.value != val)
    },
    parseFormattedDate(formattedDateString) {
      const isoDateString = formattedDateString.replace(" ", "T");
      const date = new Date(isoDateString);
      if (isNaN(date.getTime())) {
        return null;
      }
      return date;
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toISOString().slice(0, 19).replace("T", " ");
    },
    // handleInfoSubmit() {
    //   this.isLoading = true

    //   this.isPushBtn = false;
    //   this.$refs["pushform"].validate((valid) => {
    //     if (valid) {
    //       let startTime = this.formatDate(this.pushform.dateRange[0]);
    //       let endTime = this.formatDate(this.pushform.dateRange[1]);
    //       let claimStartTime = this.formatDate(this.pushform.claimdateRange[0]);
    //       let claimEndTime = this.formatDate(this.pushform.claimdateRange[1]);
    //       let queryParams = {};
    //       queryParams.startTime = startTime;
    //       queryParams.endTime = endTime;
    //       queryParams.claimStartTime = claimStartTime;
    //       queryParams.claimEndTime = claimEndTime;
    //       queryParams.groupId = this.groupId;
    //       queryParams.campaignName = this.pushform.campaignName;
    //       queryParams.campaignType = this.pushform.campaignType;
    //       queryParams.campaignDegree = this.pushform.campaignDegree;
    //       queryParams.executer = this.pushform.executer;
    //       queryParams.distributeType = this.pushform.distributeType;
    //       queryParams.claimType = this.pushform.claimType;
    //       queryParams.createRole = this.createRole;

    //       if (this.custType == '个人') {
    //         queryParams.distributeType = this.ruleMap.personal[0]?.ruleKey;
    //         queryParams.distributeType2 = this.ruleMap.personal[1]?.ruleKey;
    //         queryParams.distributeType3 = this.ruleMap.personal[2]?.ruleKey;
    //       }
    //       else if (this.custType == '商户') {
    //         queryParams.distributeType = this.ruleMap.merchant[0]?.ruleKey;
    //         queryParams.distributeType2 = this.ruleMap.merchant[1]?.ruleKey;
    //         queryParams.distributeType3 = this.ruleMap.merchant[2]?.ruleKey;
    //       }
    //       else {
    //         queryParams.distributeType = this.ruleMap.company[0]?.ruleKey || '';
    //         queryParams.distributeType2 = this.ruleMap.company[1]?.ruleKey;
    //         queryParams.distributeType3 = this.ruleMap.company[2]?.ruleKey;
    //       }

    //       campaignAdd(queryParams).then((res) => {
    //         if (res.code == "200") {
    //           this.isLoading = false
    //           Message.success(`${this.custType}分群${this.pushform.groupName}活动创建成功!`);
    //           this.getList();
    //           this.pushOpen = false;
    //           this.defaultListData = [];

    //           //将执行人类型传给详情
    //           // this.$router.push({ path: '/groupBase/customerDetail', query: { executer:this.pushform.executer} })
    //         }
    //       });
    //     } else {
    //       console.error("新增失败", error);
    //     }
    //   });
    // },
    // handlePushGroupCustomer(groupName, groupId, campaignId, row) {

    //   this.isLoading = false
    //   // console.log(groupName,'name');
    //   this.defaultListData = []
    //   let custType = row
    //   if (custType == '0') {
    //     this.custType = '个人';
    //   } else if (custType == '1') {
    //     this.custType = '商户'
    //   } else {
    //     this.custType = '企业'
    //   }

    //   this.selectOptions = [
    //     { value: 0, label: '手动指定' },
    //     { value: 1, label: `按客户归属(${this.custType})` },
    //     { value: 2, label: `按地址归属(${this.custType})` }
    //   ],
    //     this.pushOpen = true;
    //   this.pushform.groupName = groupName;
    //   // this.pushform.groupName = groupName;
    //   this.groupId = groupId;
    //   // this.campaignId = campaignId;

    //   if (campaignId == null) {

    //     this.$router.push({ path: '/taskManage/taskCreation', query: { type: '1' } })

    //   } else {
    //     campaignDetail({ campaignId: campaignId }).then((res) => {
    //       this.pushformDetail = res;
    //       if (campaignId != null) {

    //         this.ispushformread = true;
    //         this.isCustomerShow = true;
    //         this.pushform.campaignName = this.pushformDetail.campaignName;
    //         this.pushform.campaignDegree = this.pushformDetail.campaignDegree;
    //         this.pushform.campaignType = this.pushformDetail.campaignType;
    //         this.pushform.executer = this.pushformDetail.executer;
    //         this.pushform.distributeType = this.pushformDetail.distributeType;
    //         this.pushform.claimType = this.pushformDetail.claimType;
    //         this.pushform.dateRange = [
    //           this.parseFormattedDate(this.pushformDetail.startTime),
    //           this.parseFormattedDate(this.pushformDetail.endTime),
    //         ];
    //         this.pushform.claimdateRange = [
    //           this.parseFormattedDate(this.pushformDetail.claimStartTime),
    //           this.parseFormattedDate(this.pushformDetail.claimEndTime),
    //         ];
    //         const { distributeType, distributeType2, distributeType3 } = this.pushformDetail

    //         if (this.custType == '个人' && this.defaultListData.length <= 3) {
    //           this.defaultListData.push({ ruleKey: distributeType, relateType: '个人', ruleOrder: 1 },
    //             { ruleKey: distributeType2, relateType: '个人', ruleOrder: 2 }, { ruleKey: distributeType3, relateType: '个人', ruleOrder: 3 })
    //           const arr = this.defaultListData.filter(item => item.ruleKey != null)
    //           console.log(arr, 'hahaha');
    //           this.defaultListData = [...arr]


    //         } else if (this.custType == '商户' && this.defaultListData.length <= 3) {

    //           this.defaultListData.push({ ruleKey: distributeType, relateType: '商户', ruleOrder: 1 },
    //             { ruleKey: distributeType2, relateType: '商户', ruleOrder: 2 }, { ruleKey: distributeType3, relateType: '商户', ruleOrder: 3 })
    //           const arr = this.defaultListData.filter(item => item.ruleKey != null)
    //           console.log(arr, 'hahaha');
    //           this.defaultListData = [...arr]



    //         } else if (this.custType == '企业' && this.defaultListData.length <= 3) {
    //           // debugger
    //           // console.log(this.defaultListData);
    //           this.defaultListData.push({ ruleKey: distributeType, relateType: '企业', ruleOrder: 1 },
    //             { ruleKey: distributeType2, relateType: '企业', ruleOrder: 2 },
    //             { ruleKey: distributeType3, relateType: '企业', ruleOrder: 3 })
    //           const arr = this.defaultListData.filter(item => item.ruleKey != null)
    //           console.log(arr, 'hahaha');
    //           this.defaultListData = [...arr]

    //         }
    //         else {
    //           this.defaultListData = []
    //         }

    //       }

    //     });
    //   }
    // },
    // handleCancle() {
    //   // debugger
    //   // this.$router.push({path:'/customer/customerbase/segmentation'})
    //   this.custType = ''
    //   this.pushOpen = false
    //   this.getList()
    //   this.selectOptions = []
    //   this.pushform = {};
    //   this.$refs.pushform.resetFields();
    //   this.defaultListData = []
    //   this.newArr = []
    // },
    handleGroupCustExport(groupId, groupName) {
      this.download(
        `/system/group/exportData/?groupId=${groupId}`,
        {},
        `${groupName}_${new Date().getTime()}.xlsx`
      );
    },
    //判断当前用户登录身份
    isUserType() {
      isHead().then((res) => {
        // console.log(Object.keys(res)[0].startsWith('h'));

        if (Object.keys(res)[0].startsWith("h")) {
          this.radiosButonIsDisableFromMe = false;
          this.radiosButonIsDisableToMe = true;
          this.createRole = "0";
          this.isHeader = true;
        } else if (Object.keys(res)[0].startsWith("b")) {
          this.radiosButonIsDisableFromMe = false;
          this.radiosButonIsDisableToMe = false;
          this.createRole = "1";
          this.isHeader = false;
        } else if (
          Object.keys(res)[0].startsWith("m") ||
          this.$store.getters.roles[0] == "admin"
        ) {
          this.radiosButonIsDisableFromMe = false;
          this.radiosButonIsDisableToMe = false;
          this.createRole = "2";
          this.isHeader = false;
        } else {
          this.radiosButonIsDisableFromMe = false;
          this.radiosButonIsDisableToMe = false;
          this.isHeader = false;
        }
      });
    },
    handleCustDetail(
      groupId,
      groupName,
      campaignId,
      groupType,
      type,
      distributeType,
      custType,
      row,
      createRole
    ) {

      findCustListByGroupId({
        groupId,
        groupType,
        pageNum: 1,
        pageSize: 10,
      }).then((res) => {
        if (res.code == 200) {
          this.$router.push({
            path: "/groupBase/customerDetail",
            query: {
              groupId,
              groupName,
              campaignId,
              groupType,
              type,
              distributeType,
              custType,
              row,
              createRole
            },
          });
        } else {
          Message.warning('');
        }
      });

    },
    handleDelete(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DeleteGroupByGroupId(row.groupId).then(res => {
          console.log(res, 'resssssssss')
          if (res.code == 200) {
            Message.success('删除成功')
            this.getList()
          }
        })
      }).catch(() => {
        Message.info('已取消')
      })
    },
    //处理搜索
    handSearch() {
      groupList({
        groupType: this.groupFlag,
        groupName: this.searchQuery,
      }).then((res) => {
        this.groupTable = res.rows;
        this.total = this.groupTable.length;
      });
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.getList()
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.getList()
    },
    getList() {
      const params = {
        groupType: this.groupFlag,
        pageNum: this.pageNum,
        pageSize: this.pageSize,

      }
      if (this.isPublic) {
        params.type = '0'
      } else if (this.isPrivate) {
        params.type = '1'
      }
      groupList(params).then((res) => {
        this.groupTable = res.rows;
        this.total = res.total;
      });
    },
    handleTabChange() {
      //根据选中的选项更新表格数据
      switch (this.selectedTab) {
        case "我创建的":
          // this.tableData = this.myTableData;
          this.groupFlag = "1";
          this.isCreatePag = false;
          this.getList();
          this.showmap = false;
          break;
        case "推荐给我的":
          // this.tableData = this.recommendedData;
          this.groupFlag = "0";
          this.getList();
          this.isCreatePag = false;
          this.showmap = false;
          break;
        default:
          this.groupFlag = "1";
          this.getList();
        // this.tableData = this.myTableData;
      }
      this.searchQuery = "";
    },
    handleQuery() {
      this.activeType.page = 1;
      this.getList();
    },
    handelRule() { },
    handleImport() {
      this.$router.push({ name: "importCreate" });
    },
    handleRuleCreation() {
      this.$router.push({ path: '/ruleCreation' })
    },
    handleDialoClose() {
      this.showCreateDialog = false;
    },
    goBackToCreateType() {
      this.isCreatePage = false;
      this.showCreateDialog = true;
    },
    handleTransFormNumber(num) {
      let chineseNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
      return chineseNum[num]
    },
    // 导入报错弹框取消
    handleImportCancle() {
      this.importVisible = false;
      this.curGroupId = '';
      this.curGroupName = '';
      this.warningStr = '';
      this.$store.commit("SET_IMPORT_ERROR", {});
    },
    // 导入报错弹框确定
    handleErrExport() {
      this.download(
        `/system/group/exportDataError/?groupId=${this.curGroupId}`,
        {},
        `导入失败_${new Date().getTime()}.xlsx`
      );
      this.handleImportCancle();
    },
    // 打开客群导入窗口
    importCustomer() {
      this.drawerVisible = true;
    },
    handleSelectRow(val) {
      this.selection = val;
      console.log(this.selection)
    },
    // 批量添加任务
    startAddTask() {
      let diffType = false;
      let oneType = this.selection[0].custType;
      for (let i = 0; i < this.selection.length; i++) {
        if (this.selection[i].custType !== oneType) {
          diffType = true;
          break;
        }
      }
      if (diffType) {
        this.$confirm('添加失败,请选择同一类型客群。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

        })
      } else {
        this.searchCurrentExistTask({
          custType: oneType,
          // type:'0',
          // pageSize:1000,
          // pageNum:1
        });
        this.showTaskDialog = true;
      }
    },
    // 确定添加到任务
    onSubmit() {
      const that = this;
      const params = {
        campaignIds: [this.formObj.task],
        groupId: this.selection.map(item => item.groupId),
      }
      this.$refs.formObj.validate((valid) => {
        if (valid) {
          that.addGroupsToExistTask(params);
        }
      })
    },
    // 取消添加到任务
    closeTaskDialog() {
      this.showTaskDialog = false;
      this.formObj.task = '';
      // this.selection=[];
      this.$refs.selectTable.clearSelection();
    },
    // 创建新任务
    goToCreateTask() {
      const groupId = this.selection.map(item => item.groupId)
      this.$router.push({
        path: "/taskManage/taskCreation",
        query: {
          custType: this.selection[0].custType,
          groupId: JSON.stringify(groupId)
        },
      });
    },

  },

};
</script>
<style lang="scss" scoped>
// .dialog-header{
//   height: 100%;
//   max-width: 760px;
//   margin: 0 auto;
//   padding: 20px;
//   border: 1px solid #cccccc;
//   border-radius: 6px;
.select-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.priority-label {
  width: 85px;

}

.el-select {
  width: 100%;
}

.distributeList {
  .el-select {
    width: 70%;
  }
}

.el-dialog__wrapper.dialog-header {
  padding-top: 25vh;
}

.el-range-editor.el-input__inner {
  display: -webkit-inline-box !important;
  display: -ms-inline-flexbox !important;
  display: inline-flex !important;
  width: 100%;
}

// }
// .search-cnt .el-input .el-input__inner {
//     height: 44px;
//     line-height: 44px;
//     border-radius: 23px;
//     border: 1px solid #ebebeb;
//     padding-left: 24px;
// }
.el-icon-circle-plus {
  font-size: 16px;
  color: #4886f8;
  border-radius: 3px;
  // margin-right: 5px;
}

.el-icon-remove-outline {
  cursor: pointer;
  font-size: 20px;
  color: #ee2a23;
  border-radius: 3px;
  margin-left: 10px;
}

.el-icon-circle-close {
  cursor: pointer;
  font-size: 20px;
  color: #ee2a23;
  border-radius: 3px;
  margin-left: 10px;
}

.el-icon-circle-plus-letter {
  cursor: pointer;
  font-size: 14px;
  color: #4886f8;
  border-radius: 3px;
  margin-right: 5px;
}

.dialog-content {
  width: 100%;
  max-width: 760px;
  display: flex;
  flex-direction: column;
  gap: 20px;

  .group-section {
    height: 114px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px;
    border: 1px solid #cccccc;
    border-radius: 3px;

    .el-icon-edit-rule {
      width: 30px;
      height: 30px;
      // font-size: 28px;
      color: #4886f8;
      border-radius: 3px;
      margin-right: 8px;
    }

    .el-icon-add-import {
      width: 30px;
      height: 30px;
      // font-size: 28px;
      color: #4886f8;
      margin-right: 8px;
      border-radius: 3px;
    }

    .group-text {
      flex-grow: 1;

      h3 {
        color: #4886f8;
        margin: 0;
        font-size: 16px;
        margin-bottom: 5px;
      }

      p {
        margin: 0;
        font-size: 12px;
        line-height: 20px;
        font-weight: 400;
        letter-spacing: 0;
        text-align: justify;
        color: #838282;
      }
    }

    .err-text {
      p {
        font-size: 16px;
      }
    }
  }
}

.customer-wrap {
  background-color: #ffffff;
  overflow: hidden;
  box-shadow: 0 3px 8px 0 #00000017;
  border-radius: 16px 16px 0 0;

  .header-radio {
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 3px 8px 0 #00000017;

    .el-radio-button {
      flex: 1;

      ::v-deep .el-radio-button__inner {
        width: 100%;
        border: none;
        font-weight: 400;
        letter-spacing: 0.5px;
        line-height: 25px;
        font-size: 18px;
        color: #666666;
        padding: 11px 0 12px 0;
      }

      ::v-deep .el-radio-button__orig-radio:checked+.el-radio-button__inner {
        background-color: #4886f8;
        font-weight: 600;
        color: #ffffff;
      }
    }
  }
}

.title {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.checkBox {
  display: flex;

  .el-checkbox-group {
    display: flex;
    align-items: center;

    ::v-deep .el-checkbox__label {
      color: #3d3d3d;
      font-size: 12px;
      font-weight: 400;
      padding-left: 6px;
    }
  }
}

.radio-labels {
  height: 32px;
  line-height: 32px;
  color: #3d3d3d;
  font-size: 14px;
  font-weight: 400;
  margin-right: 30px;

  &::after {
    content: "*";
    left: 5px;
    color: #ff4d42;
    position: relative;
    top: 2px;
  }
}

.search-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin: 24px 0;

  .search-cnt {
    position: relative;
    width: 70%;
  }

  ::v-deep .el-input {
    width: 100%;
    position: relative;

    .el-input__inner {
      height: 44px;
      line-height: 44px;
      border-radius: 23px;
      border: 1px solid #ebebeb;
      padding-left: 24px;
    }

    .el-input__suffix {
      right: 85px;
    }
  }

  .search-btn {
    width: 80px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 0;
    top: 2px;
    border: 1px solid #4886f8;
    background-color: #4886f8;
    border-radius: 20px;
    cursor: pointer;
    z-index: 1;

    .el-icon-search {
      color: #ffffff;
      font-size: 14px;
    }
  }
}

a {
  color: rgb(7, 58, 177);
  text-decoration: none;
}

.main-wrap {
  margin: 0 30px;

  .checkBox {
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
}

.dialog-content>el-button {
  margin-bottom: 20px;
}

.operate-cnt {
  margin: 24px 0 16px 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;

  .plain-raido-btn {
    ::v-deep .el-radio-button__inner {
      color: #666666;
      font-size: 14px;
      font-weight: 400;
      border: 1px solid #ebebeb;
      border-radius: 0;
    }

    ::v-deep .el-radio-button__orig-radio:checked+.el-radio-button__inner {
      border: 1px solid #4886f8;
      color: #4886f8;
      background-color: #ffffff;
      box-shadow: none;
    }
  }
}

.label-box {
  display: inline-block;
  position: relative;
}

.quesiton {
  display: block;
  font-size: 13px;
  color: #b9b9b9;
  position: absolute;
  right: -14px;
  top: -5px;
}

.child-main {

  // padding: 40px 40px;
  .my-form {
    margin: 10px 0 30px 0;
    text-align: center;
  }

  .title {
    font-size: 20px;
  }

  .dialog-footer {
    text-align: center;

    .handle-btn {
      margin-left: 10px;
    }
  }

  ::v-deep .el-form-item__error {
    margin-left: 70px;
  }
}

::v-deep .v-step::after {
  content: '';
  position: absolute;
  width: 100px;
  height: 100px;
  background-image: url('../../../../assets/images/arrow.gif');
  background-repeat: no-repeat;
  background-size: contain;
  top: 0;
  left: 50%;
  z-index: 9999999;
}

::v-deep .v-step[data-popper-placement^="top"]::after {
  top: 35px;
  left: -40%;

}

::v-deep .v-step[data-popper-placement^="bottom"]::after {
  top: -60%;
  left: 0;
  transform: rotate(90deg);
}

::v-deep .v-step[data-popper-placement^="left"]::after {
  top: -50%;
  left: 155%;
}

::v-deep .v-step[data-popper-placement^="right"]::after {
  top: -55%;
  left: -80%;

}
</style>
<style>
@import '../../../grid/tour.css';
</style>