<template>
  <div class="common-wrap-cnt">
    <section class="common-create-main" v-if="showSearch">
      <el-input v-model="custName" style="width: 15%; margin-left: 18px" placeholder="请输入客户名称"
        @clear="getSelectCustomerData" @keyup.enter.native="getSelectCustomerData" clearable size="small"
        prefix-icon="el-icon-search" />
      <el-input style="width: 15%;margin-left: 30px;" v-model="custIdc" placeholder="请输入身份证号" clearable size="small"
        @keyup.enter.native="getSelectCustomerData" @clear="getSelectCustomerData" prefix-icon="el-icon-search" />
        <el-select 
          style="width: 15%;margin-left: 30px;" 
          v-model="pushStatus" 
          clearable
          @clear="getSelectCustomerData"
          size="small"
          placeholder="请选择导入状态"
         >
            <el-option v-for="item in pushStatusList" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
        </el-select>
      <el-button type="primary" @click="getSelectCustomerData" style="margin-left: 80px">查询</el-button>
      <el-button @click="handleFilterClear" style="margin-left: 20px">重置</el-button>
      <!-- <el-button type="text" :class="handClassStyle" @click="
        () => {
          this.isShowFilter = !this.isShowFilter;
        }
      ">{{ this.isShowFilter == true ? "收起" : "展开" }}</el-button> -->
    </section>
    <section class="common-create-main" v-if="isShowFilter" style="margin-left:20px">


    </section>
    <section class="operate-cnt">
      <div style="display: flex; justify-content: space-between; width: 5%;padding-left: 20px;">
        <el-button type="primary" :disabled="selectedRows.length === 0" icon="el-icon-plus" @click="showTaskDialog=true">批量添加任务</el-button>
        <el-button type="primary" size="small" icon="el-icon-download" @click="exportDataByCustIds">导出</el-button>
        <el-button type="primary" size="small" icon="el-icon-upload" @click="importData">导入</el-button>
        <el-button round size="small" @click="searchImportErr">导入失败</el-button>
      </div>
      <div style="display: flex; justify-content: space-between">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="handleRefersh" :columns="columns"
          style="margin-right: 25px; margin-top: 15px"></right-toolbar>
        <el-button @click="returnLastPage">返回上一级</el-button>
      </div>
    </section>

    <section class="table-wrap">
      <el-table :data="custTableData" style="width: 100%; margin-top: 20px" ref="groupCustomerDetail"
        @selection-change="handleSelectionChange" max-height="635">
        <el-table-column prop="groupId" type="selection" label="全选"></el-table-column>
        <el-table-column prop="custName" align="center" label="客户名称" v-if="columns[0].visible">
           <template slot-scope="scope">
              <el-button type="text" @click="openDialog(scope.row.custId)" class="special-btn">{{scope.row.custName}}</el-button>
            </template>
        </el-table-column>
        <el-table-column prop="idType" align="center" label="证件类型" v-if="columns[1].visible" show-overflow-tooltip></el-table-column>
        <el-table-column prop="custIdc" align="center" label="证件号" v-if="columns[2].visible" show-overflow-tooltip>
          <template slot-scope="scope">
              <el-button type="text" @click="openDialog(scope.row.custId)" class="special-btn">{{scope.row.custIdc}}</el-button>
            </template>
        </el-table-column>
        <el-table-column prop="custPhone" align="center" label="联系方式" v-if="columns[3].visible" show-overflow-tooltip></el-table-column>
        <el-table-column prop="custId" align="center" label="客户号" v-if="columns[4].visible" show-overflow-tooltip></el-table-column>
        <el-table-column prop="deptName" align="center" label="推送支行" v-if="columns[5].visible" show-overflow-tooltip></el-table-column>
        <el-table-column prop="outlets" align="center" label="推送网点" v-if="columns[6].visible" show-overflow-tooltip></el-table-column>
        <el-table-column prop="tellerNameWithId" align="center" label="推送客户经理" v-if="columns[7].visible" show-overflow-tooltip></el-table-column>
        <el-table-column prop="custLb" align="center" label="是否我行内客户" v-if="columns[8].visible">
          <template slot-scope="scope">
            {{scope.row.custLb == '0'?'是':scope.row.custLb == '1'?'否':''}}
          </template>
        </el-table-column>
        <el-table-column prop="pushStatus" align="center" label="导入状态" v-if="columns[9].visible">
          <template slot-scope="scope">
            {{scope.row.pushStatus == '2'?'失败':scope.row.pushStatus == '1'?'成功':''}}
          </template>
        </el-table-column>
        <el-table-column prop="remark" align="center" label="备注" v-if="columns[10].visible" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" align="center" label="导入时间" v-if="columns[11].visible"></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>
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
        <el-input :placeholder="isbranch ? '请输入个人柜员号或姓名' : (executer == 0 ? '请输入机构名' : '请输入机构名称/个人柜员号/个人名称')"
          v-model="searchParams" clearable @clear="resetSearch" @keyup.enter.native="handleTreeSearch">
          <template slot="append">
            <el-button icon="el-icon-refresh" @click="resetSearch"></el-button>
          </template>
        </el-input>
        <div class="roll-dialog" v-loading="treeLoading">
          <el-tree class="tree-border" :data="deptOptions" show-checkbox :check-strictly="true"
            :filter-node-method="filterNode" @check-change="handleCheckChange" ref="deptTree" node-key="id"
            empty-text="加载中，请稍候" :props="defaultDeptProps" :style="{ width: '100%' }"></el-tree>
        </div>

        <span slot="footer">
          <el-button @click="handleDialogCancle">取消</el-button>
          <el-button type="primary" @click="handleConfigeInfo">确定</el-button>
        </span>
      </el-dialog>
    </section>
    <CustomerImport :drawerVisible="drawerVisible" @closeDrawer="closeDrawer" :taskOptions="taskOptions" :groupId="groupId" :groupName="groupName" :custType="custType"/>
    <div class="dialog-container">
      <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="请选择任务">
                    <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 @click="showTaskDialog=!showTaskDialog">取消</el-button>
              <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 {
  isHead,
  findCustListByGroupId,
  campaignDetail,
  customerAppoint,
  findCustomerByNameAndId,
  exportDataError,
} from "@/api/system/findCustByGroupId.js";
import { getDeptTree, getDeptUserTree } from "@/api/grid/address/tree.js";
import { Message } from "element-ui";
import { getUserProfile } from "@/api/system/user";
import CustomerImport from '../../components/customer-import.vue'
import { getCurrentExistTask,addToCurrentExistTask } from "@/api/system/grouplist";

export default {
   components: {
    CustomerImport
  },
  props: {
    createRoleC: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      treeLoading: true,
      dialogTitle: '',
      nowDeptName: '',
      gridName2: '',
      gridName: '',
      custIdc: '',
      custIsn: '',
      socialCreditCode: '',
      outlets: '',
      deptName: '',
      userName: '',
      isShowFilter: false,
      showSearch: true,
      columns: [
        { key: 0, label: `客户名称`, visible: true,prop:"custName" },
        { key: 1, label: `证件类型`, visible: true,prop:"idType" },
        { key: 2, label: `证件号`, visible: true,prop:"custIdc" },
        { key: 3, label: `联系方式`, visible: true,prop:"custPhone" },
        { key: 4, label: `客户号`, visible: true,prop:"custId" },
        { key: 5, label: `推送支行`, visible: true,prop:"deptName" },
        { key: 6, label: `推送网点`, visible: true,prop:"outlets" },
        { key: 7, label: `推送客户经理`, visible: true,prop:"tellerNameWithId" },
        { key: 8, label: `是否我行内客户`, visible: true,prop:"custLb" },
        { key: 9, label: `导入状态`, visible: true,prop:"pushStatus" },
        { key: 10, label: `备注`, visible: true ,prop:"remark"},
        { key: 11, label: `导入时间`, visible: true ,prop:"createTime"},
      ],
      currentPage: 1,
      userIds: [],
      hasCheck: false,
      userIds: [],
      deptid: 0,
      campaignId: "",
      checkedDeptIds: [],
      deptOptions: [],
      filteredTreeData: [],
      filterTreeData: [],
      searchParams: "",
      dialogVisible: false,
      selectedRows: [],
      custId: "",
      groupId: "",
      custTableData: [],
      groupName: "",
      custName: "",
      pushStatus: "",
      pageSize: 10,
      pageNum: 1,
      total: 0,
      type: 0,
      deptName: "",
      selectedIds: [],
      executer: "",
      checkedKeys: [],
      children: [],
      distributeType: 0,
      groupType: "",
      isorgName: true,
      isgridName: false,
      isuserName: false,
      isbranch: false,
      isHead: false,
      input: '',
      currentDeptId: '',
      deptidArr: [],
      deptUser: [],
      allUserList: [],
      defaultDeptProps: {
        children: "children",
        label: "label",
        // disabled: (data) =>{
        //   if(this.isHead) {
        //       return !['branch', "outlet", "user"].includes(data.level)
        //   }
        //   // else if(this.isbranch){
        //   //    return ![ "outlet", "user"].includes(data.level)
        //   // }
        // }

      },
      drawerVisible:false,
      showTaskDialog:false,
      formObj:{
        task:''
      },
      formRules: {
        task: [
          { 
            required: true, 
            message: '任务不能为空',
            trigger: 'blur'
          },
        ]
      },
      custType:'0',
      pushStatusList:[
        {label:'成功',value:'1'},
        {label:'失败',value:'2'}
      ],
      taskOptions:[]
    };
  },
  computed: {
    handClassStyle() {
      return this.isShowFilter == true ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
    }
  },
  watch: {
    searchParams(val) {
      this.$refs.deptTree.filter(val)
    }
  },
  created() {
    this.isUserType();
  },
  mounted() {
    getUserProfile().then((res) => {
      this.nowDeptName = res.data.dept.deptName
      this.currentDeptId = res.data.deptId;
    });
    findCustomerByNameAndId({ input: this.input }).then(res => {
      this.deptUser = res.filter(item => item.deptId != '999000');
      this.deptidArr = this.deptUser.map(item => item = item.deptId)

    })

    const type = this.$route.query.type;
    this.type = type;
    const distributeType = this.$route.query.distributeType;
    this.distributeType = distributeType;
    isHead().then((res) => {
      if (Object.keys(res)[0].startsWith("b")) {
        this.createRole = "1";
        this.isbranch = true;
        this.isHead = false;
      }
      if (Object.keys(res)[0].startsWith("h")) {
        this.createRole = "0";
        this.isbranch = false;
        this.isHead = true;
      }
    });
    // this.handleLoadTreeData({deptid:'801010'})
    this.groupId = this.$route.query.groupId;
    this.id = this.$route.query.groupId;
    this.groupType = this.$route.query.groupType;
    this.campaignId = this.$route.query.campaignId;
    campaignDetail({ campaignId: this.campaignId }).then((res) => {
      this.executer = res.executer;
      //机构
      if (this.executer == "0") {
        this.isorgName = true;
        this.isgridName = false;
        this.isuserName = false;
      }
      //个人
      if (this.executer == "1") {
        this.isorgName = false;
        this.isgridName = true;
        this.isuserName = true;
      }
      //混合
      if (this.executer == "2") {
        this.isorgName = true;
        this.isgridName = true;
        this.isuserName = true;
      }
    });
    const groupName = this.$route.query.groupName;
    this.groupName = groupName;
    this.getCustomerDetail();
    this.initCustomerByNameAndId()
    this.searchCurrentExistTask({
      custType:'0',
      // type:'0',
      // pageSize:1000,
      // pageNum:1
    })
    console.log(this.$route.query,3333)
  },
  methods: {
    openDialog(custId) {
        this.$router.push({
        path: '/360charts/indexcharts',
          query: {
              custId
          }
        })
      },
    // 获取当前已有任务
    searchCurrentExistTask(params){
      getCurrentExistTask(params).then(res=>{
        if(res.code == 200){
          this.taskOptions = res.data.map(item=>{
            return {
              label:item.campaignName,
              value:item.campaignId,
            }
          }) ;
        }
      })
    },
    // 添加客群到已选任务
    addGroupsToExistTask(){
      addToCurrentExistTask(params).then(res=>{
        if(res.code == 200){
          
        }
      })
    },
    //获取所有的用户列表
    initCustomerByNameAndId() {
      findCustomerByNameAndId().then((res) => {
        let list = res.filter(
          (item) => item.deptId != `${item.deptId.substring(0, 3)}000`
        );
        this.allUserList = list.map((item) => {
          return {
            label: `${item.nickName}(${item.userName})`,
            value: item.userName,
            deptId: item.deptId,
            id: item.userId,
            level: "user",
            children: [],
          };
        });
        // console.log(this.allUserList)
      });
    },
    //判断当前用户登录身份
    isUserType() {

      isHead().then((res) => {

        if (Object.keys(res)[0].startsWith("h")) {
          this.radiosButonIsDisableFromMe = false;
          this.radiosButonIsDisableToMe = true;
          this.isorgName = true;
          this.isgridName = true;
          this.isuserName = true;
          this.createRole = "0";
        } else if (Object.keys(res)[0].startsWith("b")) {
          this.radiosButonIsDisableFromMe = false;
          this.radiosButonIsDisableToMe = false;
          this.createRole = "1";
          this.isorgName = true;
          this.isgridName = true;
          this.isuserName = true;
        } else if (
          Object.keys(res)[0].startsWith("m") ||
          this.$store.getters.roles[0] == "admin"
        ) {
          this.radiosButonIsDisableFromMe = false;
          this.radiosButonIsDisableToMe = false;
          this.createRole = "2";
          this.isorgName = true;
          this.isgridName = true;
          this.isuserName = true;
        } else {
          this.radiosButonIsDisableFromMe = false;
          this.radiosButonIsDisableToMe = false;
        }
      });
    },
    handleDialogCancle() {
      this.deptOptions = []
      this.treeLoading = true
      this.searchParams = ''
      this.$refs.groupCustomerDetail.clearSelection()
      this.dialogVisible = false;
      this.checkedKeys = [];
      this.userIds = []
    },
    handlenodeClick(data) {
    },

    handleoneSend(row) {
      this.$refs.groupCustomerDetail.toggleRowSelection(row, true);
    },
    handleConfigeInfo() {
      //总行管理员和机构

      if (this.executer == 0 && this.isHead) {
        if (this.checkedKeys.length == 0) {
          Message.warning('请勾选机构后提交')
        } else {
          customerAppoint({
            custIds: this.selectedIds?.join(",") || this.custIds,
            deptIds: this.checkedKeys?.join(",") || [],
            groupId: this.groupId,
            campaignId: this.campaignId,
            createRole: this.createRole,
          }).then((res) => {

            if (res.code == "200") {
              Message.success("总行机构层级推送成功!");
              this.deptOptions = []
              this.checkedKeys = []
              this.treeLoading = true
              this.searchParams = ''
              this.dialogVisible = false
              this.selectedRows.map((item) => {
                return (item.pushStatus = "1")
              })
              this.$refs.groupCustomerDetail.clearSelection()
              this.userIds = []
              this.getCustomerDetail()

            }
          });
        }

      }
      //推送到个人的情况
      else if (this.executer == 1 && this.isHead) {
        if (this.userIds.length == 0) {
          Message.warning('请勾选客户经理后提交')
        } else {
          customerAppoint({
            custIds: this.selectedIds.join(",") || this.custIds,
            deptIds: "",
            userIds: [...new Set(this.userIds)].join(","),
            groupId: this.groupId,
            campaignId: this.campaignId,
            createRole: this.createRole,
          }).then((res) => {
            if (res.code == "200") {
              Message.success("总行个人层级推送成功！");
              this.deptOptions = []
              this.treeLoading = true
              this.searchParams = ''
              this.dialogVisible = false;
              this.selectedRows.map((item) => {
                return (item.pushStatus = "1");
              });
              this.$refs.groupCustomerDetail.clearSelection();
              this.userIds = []
              this.getCustomerDetail()
            }
          });
        }

      } else if (this.isbranch == true) {
        if (this.userIds.length == 0) {
          Message.warning('请勾选客户经理后提交')
        } else {
          customerAppoint({
            custIds: this.selectedIds.join(",") || this.custIds,
            deptIds: "",
            userIds: [...new Set(this.userIds)].join(","),
            groupId: this.groupId,
            campaignId: this.campaignId,
            createRole: this.createRole,
          }).then((res) => {

            if (res.code == "200") {
              Message.success("支行个人推送成功！");
              this.deptOptions = []
              this.treeLoading = true
              this.searchParams = ''
              this.dialogVisible = false;
              this.selectedRows.map((item) => {
                return (item.pushStatus = "1");
              });
              this.$refs.groupCustomerDetail.clearSelection();
              this.userIds = []
              this.getCustomerDetail()
            }
          });
        }

      } else if (this.executer == 2 && this.isHead) {
        if (this.userIds.length == 0 && this.checkedKeys.length == 0) {
          Message.warning('请至少选择一个机构及客户经理进行混合推送')
        } else {
          customerAppoint({
            custIds: this.selectedIds.join(",") || this.custIds,
            deptIds: this.checkedKeys.join(","),
            userIds: [...new Set(this.userIds)].join(","),
            groupId: this.groupId,
            campaignId: this.campaignId,
            createRole: this.createRole,
          }).then((res) => {
            if (res.code == 200) {
              Message.success("总行混合推送成功");
              this.deptOptions = []
              this.treeLoading = true
              this.searchParams = ''
              this.dialogVisible = false;
              this.selectedRows.map((item) => {
                return (item.pushStatus = "1");
              });
              this.$refs.groupCustomerDetail.clearSelection();
              this.userIds = []
              this.checkedKeys = []
              this.getCustomerDetail()
            }
          });
        }

      }
    },
    exportDataByCustIds() {
      if (this.selectedIds.length == 0) {
        Message.warning("请先选择导出客户");
        return;
      }
      // 找出筛选的列
      const choosedColumns = this.columns.filter(item=>item.visible);
      const keys = choosedColumns.map(item=>item.prop);
      const custIds = this.selectedRows.map((item) => {
        return (item = item.custId);
      });
      this.download(
        `/system/group/exportDataByCustIds/?groupId=${this.groupId
        }&custIds=${custIds.join(",")}&exportType=${keys.join(",")}`,
        {},
        `个人分群_${new Date().getTime()}.xlsx`
      );
      this.$refs.groupCustomerDetail.clearSelection();
      Message.success("导出成功");
    },
    handleCheckChange(data, checked) {
      if (this.isbranch) {
        if (checked) {
          this.userIds.push(data.id);
        } else if (!checked && this.userIds != []) {
          const index = this.userIds.indexOf(data.id);
          this.userIds.splice(index, 1);
        }
      }
      if (this.executer == "0") {
        if (checked) {
          this.checkedKeys.push(data.id);
        } else if (!checked && this.checkedKeys != []) {
          const index = this.checkedKeys.indexOf(data.id);
          this.checkedKeys.splice(index, 1);
        }
      }
      if (this.executer == "1" && data.level == "user") {
        if (checked) {
          this.userIds.push(data.id);
        } else if (!checked && this.userIds != []) {
          const index = this.userIds.indexOf(data.id);
          this.userIds.splice(index, 1);
        }
      }
      if (this.executer == "2" && this.isHead) {
        if (data.level != "user") {
          if (checked) {
            this.checkedKeys.push(data.id);
          } else if (!checked && this.checkedKeys != []) {
            const index = this.checkedKeys.indexOf(data.id);
            this.checkedKeys.splice(index, 1);
          }
        } else {
          if (checked) {
            this.userIds.push(data.id);
          } else if (!checked && this.userIds != []) {
            const index = this.userIds.indexOf(data.id);
            this.userIds.splice(index, 1);
          }
        }
      }
    },
    resetSearch() {
      this.searchParams = "";
      if (this.createRole == "0") {
        //总行
        if (this.executer == '0') {
          //机构
          this.dialogTitle = '请选择机构'
          this.getDeptTree()
        } else if (this.executer == '1') {
          //个人
          this.dialogTitle = '请选择客户经理'
          this.getPersonTree();
        } else {
          //混合
          this.dialogTitle = '请选择个人或者机构'
          this.getDeptAndPerTree();
        }
      } else if (this.createRole == "1") {
        this.dialogTitle = '请选择客户经理'
        this.getZhpersonTres()
      }

    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleTreeSearch() {
      // this.filterTreeData = this.filterTree(
      //   this.deptOptions,
      //   this.searchParams
      // );
      // if (this.searchParams) {
      //   this.deptOptions = this.filterTreeData[0].children;
      // }
      // getDeptTree();
    },
    // filterTree(data, searchQuery) {
    //   if (!searchQuery) {
    //     return data;
    //   }
    //   const filteredData = data.filter((node) => {
    //     // 检查当前节点的label是否包含搜索关键字
    //     if (node.label.toLowerCase().includes(searchQuery.toLowerCase())) {
    //       return true;
    //     }
    //     // 如果当前节点有子节点，则递归检查子节点
    //     if (node.children && node.children.length > 0) {
    //       const filteredChildren = this.filterTree(node.children, searchQuery);
    //       // 如果子节点被过滤出来了，保留当前节点
    //       if (filteredChildren.length > 0) {
    //         node.children = filteredChildren;
    //         return true;
    //       }
    //     }
    //     // 如果当前节点不符合条件且没有符合条件的子节点，则不包含当前节点
    //     return false;
    //   });

    //   return filteredData;
    // },
    getAllNodesUnderBFS(tree, id) {
      const result = [];
      const queue = [tree];
      while (queue.length > 0) {
        const currentNode = queue.shift();
        if (currentNode.id === id) {
          result.push(currentNode);
          if (currentNode.children && currentNode.length > 0) {
            queue.push(...currentNode.children);
          }
        } else {
          if (currentNode.children && currentNode.length > 0) {
            queue.push(...currentNode.children);
          }
        }
      }
      return result;
    },
    //总行---机构树
    getDeptTree() {
      getDeptTree().then((response) => {
        this.deptOptions = response.data;
        this.treeLoading = false
      })
    },
    //总行---个人树
    getPersonTree() {
      console.log(this.allUserList, 'this.allUserList')
      getDeptTree().then((response) => {
        this.deptOptions = response.data;
        this.deptOptions[0].disabled = true
        this.deptOptions[0].children.forEach((item) => {
          this.allUserList.forEach((el) => {
            if (item.level == "branch") {
              item.disabled = true
              if (item.id == el.deptId) {
                item.children ? item.children.push(el) : [];

              }
            }
          });
        });
        this.deptOptions[0].children.forEach((item) => {
          if (Array.isArray(item.children)) {
            item?.children.forEach((el) => {
              el.children = [];
              if (el.level == "outlet") {
                el.disabled = true
                this.allUserList.forEach((v) => {
                  if (el.id == v.deptId) {
                    el.children.push(v);
                  }
                });
              }
            });
          }
        });
        this.treeLoading = false
      });
    },
    //总行---混合树
    getDeptAndPerTree() {
      getDeptTree().then((response) => {
        this.deptOptions = response.data;
        console.log(this.deptOptions, 'this.deptOptionsthis.deptOptions')
        this.deptOptions[0].children.forEach((item) => {
          this.allUserList.forEach((el) => {
            if (item.level == "branch") {
              if (item.id == el.deptId) {
                item.children ? item.children.push(el) : [];
              }
            }
          });
        });
        this.deptOptions[0].children.forEach((item) => {
          if (Array.isArray(item.children)) {
            item?.children.forEach((el) => {
              el.children = [];
              if (el.level == "outlet") {
                this.allUserList.forEach((v) => {
                  if (el.id == v.deptId) {
                    el.children.push(v);
                  }
                });
              }
            });
          }
        });
        this.treeLoading = false
      });
    },
    //支行---个人树
    getZhpersonTres() {
      getDeptTree({ deptid: this.currentDeptId }).then((response) => {
        this.deptOptions = response.data;
        this.deptOptions[0].disabled = true
        this.deptOptions[0].children.forEach((item) => {
          item.children = [];
          item.disabled = true
          this.allUserList.forEach((el) => {
            if (this.deptOptions[0].id == el.deptId) {

              this.deptOptions[0].children.push(el)
              this.deptOptions[0].children = Array.from(new Set(this.deptOptions[0].children))
            }
            if (item.level == "outlet") {
              if (item.id == el.deptId) {
                item.children.push(el)
              }
            }
          });
        });
      });
      this.treeLoading = false
    },
    handleCustAppointOne(custId) {
      if (this.campaignId == null) {
        Message.warning("请返回上一级，新建活动成功后才可指定推送！");
        this.$refs.groupCustomerDetail.clearSelection();
        return;
      }
      this.dialogVisible = true;
      this.custIds = custId;
      if (this.createRole == "0") {
        //总行
        if (this.executer == '0') {
          //机构
          this.dialogTitle = '请选择机构'
          this.getDeptTree()
        } else if (this.executer == '1') {
          //个人
          this.dialogTitle = '请选择客户经理'
          this.getPersonTree();
        } else {
          //混合
          this.dialogTitle = '请选择个人或者机构'
          this.getDeptAndPerTree();
        }
      } else if (this.createRole == "1") {
        //支行----只能选择推送给个人
        this.dialogTitle = '请选择客户经理'
        this.getZhpersonTres()
      }

      // this.getAllDeptUser()
    },
    handleCustAppoint() {
      if (this.selectedIds.length == 0) {
        Message.warning("请先选择指定客户");
        return;
      }
      if (this.campaignId == null) {
        Message.warning("请返回上一级，新建活动成功后才可批量推送！");
        this.$refs.groupCustomerDetail.clearSelection();
        return;
      }
      this.dialogVisible = true;
      if (this.createRole == "0") {
        //总行
        if (this.executer == '0') {
          //机构
          this.dialogTitle = '请选择机构'
          this.getDeptTree()
        } else if (this.executer == '1') {
          //个人
          this.dialogTitle = '请选择客户经理'
          this.getPersonTree();
        } else {
          //混合
          this.dialogTitle = '请选择个人或者机构'
          this.getDeptAndPerTree();
        }
      } else if (this.createRole == "1") {
        //支行----只能选择推送给个人
        this.dialogTitle = '请选择客户经理'
        this.getZhpersonTres()
      }

    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      const selectedCustIds = this.selectedRows.map((item) => item.custId);
      this.selectedIds = selectedCustIds;
    },
    returnLastPage() {
      this.type == 0
        ? this.$router.push({ path: "/grid/create/segmentation" })
        : this.$router.push({ path: "/taskManage/checklist" });
    },
    handleFilterClear() {
      this.custName = ''
      this.pushStatus = ''
      this.custId = ''
      this.groupType = ''
      this.gridName2 = ''
      this.gridName = ''
      this.custIdc = ''
      this.custIsn = ''
      this.outlets = ''
      this.deptName = ''
      this.userName = ''
      this.getSelectCustomerData()
    },
    handleStatus(status) {
      switch (status) {
        case "0":
          return "未推送";
        case "1":
          return "推送成功";
        case "2":
          return "推送失败";
      }
    },
    // 分页
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      // this.getCustomerDetail();
      this.getSelectCustomerData()
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      // this.getCustomerDetail();
      this.getSelectCustomerData()
    },
    getCustomerDetail() {
      const params = {
        groupId: this.groupId,
        groupType: this.groupType,
        pageNum: this.pageNum,
        pageSize: this.pageSize,

      }
      findCustListByGroupId(params).then((res) => {
        this.custTableData = res.rows
        this.total = res.total;
      });
    },
    handleRefersh() {
      this.custName = ''
      this.custIdc = ''
      this.custIsn = ''
      this.gridName = ''
      this.gridName2 = ''
      this.userName = ''
      this.pageNum = 1
      this.pageSize = 10
      this.getSelectCustomerData()
    },
    //筛选查询
    getSelectCustomerData() {
      findCustListByGroupId({
        groupId: this.groupId,
        custName: this.custName,
        // pushStatus: this.pushStatus[0],
        custId: this.custId,
        groupType: this.groupType,
        gridName2: this.gridName2,
        gridName: this.gridName,
        custIdc: this.custIdc,
        custIsn: this.custIsn,
        outlets: this.outlets,
        deptName: this.deptName,
        userName: this.userName,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        pushStatus:this.pushStatus,
      }).then((res) => {
        this.custTableData = res.rows;
        this.total = res.total;
      });
    },
    // 导入
    importData(){
      this.drawerVisible=true;
    },
    // 关闭导入窗口
    closeDrawer(refresh){
      this.drawerVisible=false;
      if(refresh == 'refresh'){
        this.getCustomerDetail();
      }
    },
    // 导出失败数据
    // exportErrData(){
    //   this.download(
    //     `/system/group/exportDataError/?groupId=${this.groupId
    //     }`,
    //     {},
    //     `导入失败_${new Date().getTime()}.xlsx`
    //   );
    // },

    searchImportErr(){
      this.pushStatus = this.pushStatus === '2'?'':'2';
      this.getSelectCustomerData();
    },
    
    // 确定添加到任务
    onSubmit() {
      const that = this;
      const params={
        campaignIds:[this.formObj.task],
        groupId:[this.groupId],
        custIds:this.selectedRows.map(item=>item.custId)
      }
      this.$refs.formObj.validate((valid) => {
        if (valid) {
          that.addGroupsToExistTask(params);
        }
      })
    },
    // 添加客群到已选任务
    addGroupsToExistTask(params){
      addToCurrentExistTask(params).then(res=>{
        if(res.code == 200){
          this.closeTaskDialog();
          Message.success('添加成功');
        }
      })
    },
     // 取消添加到任务
    closeTaskDialog(){
      this.showTaskDialog=false;
      this.formObj.task='';
      // this.selection=[];
      this.$refs.groupCustomerDetail.clearSelection();
    },
    // 取消添加到任务
    onCancel(){
      this.closeTaskDialog();
    },
    // 创建新任务
    goToCreateTask(){
       this.$router.push({
        path: "/taskManage/taskCreation",
        query: {
         
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./../../create-style.scss";

.file-upload {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: space-between;
  height: 320px;

  .group-input {
    width: 702px;
    height: 288px;
    margin-top: 25px;
  }

  .group-select {
    width: 702px;
    height: 288px;
    margin-top: 25px;
  }

  .file-upload-bg {
    width: 702px;
    height: 288px;
    background: #f7f8fa;
    // display: flex;
    // align-items: center;
    // justify-content: center;
  }

  .el-icon-upload {
    text-align: center;
    font-size: 47.36px;
    color: #cccccc;
  }

  .file-upload-desc {
    font-weight: 400;
    font-size: 14px;
    color: #666666;
    letter-spacing: 0;
    text-align: center;
    line-height: 12px;
    margin-top: 8px;
  }

  .file-upload-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    margin-top: 20px;
  }

  .file-upload-download {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    margin-top: 15px;
    font-size: 14px;
  }

  .file-upload-progress {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    margin-top: 15px;
    font-size: 14px;
  }
}

.preview-table {
  width: 100%;
  margin-top: 16px;
}

.preview-cnt {
  margin-top: 40px;
}

.chose-cnt {
  ::v-deep .el-form-item__content {
    display: flex;
    justify-content: space-between;

    .el-button {
      width: 88px;
      margin-left: 24px;
    }

    .el-select {
      flex: 1;
    }
  }
}

.el-icon-arrow-up {
  font-size: 16px;
  margin-left: 20px;
}

.el-icon-arrow-down {
  font-size: 16px;
  margin-left: 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;
    }
  }
}
.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;
    }
  }
  .special-btn{
        width: 112%;
        overflow: hidden;
        text-overflow: ellipsis;
    }
</style>
