<template>
  <div class="app-container">
    <!-- 筛选框 -->
    <el-row :gutter="24" style="display: flex; align-items: center">
      <el-col :span="4">
        <!-- 客户号查询 -->
        <el-input
          v-model="custId"
          placeholder="请输入客户号"
          clearable
          size="small"
          @keyup.enter.native="getSelectCustomerData"
          @clear="getSelectCustomerData"
          prefix-icon="el-icon-search"
        />
      </el-col>
      <el-col :span="4">
        <!-- 客户号查询 -->
        <el-input
          v-model="custName"
          placeholder="请输入客户名称"
          @clear="getSelectCustomerData"
          @keyup.enter.native="getSelectCustomerData"
          clearable
          size="small"
          prefix-icon="el-icon-search"
        />
      </el-col>
      <el-col :span="4">
        <!-- 推送状态 -->
        <el-select
          v-model="pushStatus"
          placeholder="请选择推送状态"
          clearable
          @clear="getSelectCustomerData"
          @change="getSelectCustomerData"
          style="width: 180px"
        >
          <el-option label="未推送" value="0"></el-option>
          <el-option label="推送成功" value="1"></el-option>
          <el-option label="推送失败" value="2"></el-option>
        </el-select>
      </el-col>
      <el-col :span="12">
        <el-button type="primary" @click="getSelectCustomerData"
          >查询</el-button
        >
        <el-button type="info" @click="handleFilterClear">重置</el-button>
        <el-button type="success" @click="handleCustAppoint"
          >批量指定</el-button
        >
        <el-button type="warning" @click="exportDataByCustIds">导出</el-button>
        <el-button @click="returnLastPage">返回上一级</el-button>
      </el-col>
    </el-row>
    <!-- 表格区域 -->
    <right-toolbar
      :getSelectCustomerData.sync="getSelectCustomerData"
      @queryTable="getSelectCustomerData"
      :columns="columns"
    ></right-toolbar>
    <el-table
      :data="paginatedData"
      style="width: 100%; margin-top: 20px"
      ref="groupCustomerDetail"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        prop="groupId"
        type="selection"
        label="全选"
      ></el-table-column>
      <el-table-column
        prop="groupName"
        align="center"
        label="分群名称"
        sortable
        v-if="columns[0].visible"
      ></el-table-column>
      <el-table-column
        prop="custName"
        align="center"
        label="客户姓名"
        sortable
        v-if="columns[1].visible"
      ></el-table-column>
        <el-table-column
        prop="custId"
        align="center"
        label="客户号"
        sortable
        v-if="columns[2].visible"
      ></el-table-column>
      <el-table-column
        prop="custIdc"
        align="center"
        label="身份证号"
        sortable
        v-if="columns[3].visible"
      ></el-table-column>
      <el-table-column
        prop="pushStatus"
        align="center"
        label="推送状态"
        sortable
        v-if="columns[4].visible"
      >
        <template slot-scope="scope">
          <span>
            {{ handleStatus(scope.row.pushStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        sortable
        prop="deptName"
        align="center"
        label="归属机构"
        v-if="isorgName&&columns[5].visible"
      ></el-table-column>
      <el-table-column
        sortable
        prop="gridName"
        align="center"
        label="所属网格"
        v-if="isgridName&&columns[6].visible"
      ></el-table-column>
      <el-table-column
        sortable
        prop="userName"
        align="center"
        label="归属执行人"
        v-if="isuserName&&columns[7].visible"
      ></el-table-column>
      <!-- 其他列 --> 
      <el-table-column fixed="right" align="center" label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleCustAppointOne(scope.row.custId)"
            >指定推送</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,sizes,prev,pager,next,jumper"
      :total="custTableData.length"
      :current-page="currentPage"
    ></el-pagination>
    <el-dialog title="选择机构/个人" :visible.sync="dialogVisible" width="30%">
      <el-input
        placeholder="请输入机构名称"
        v-model="searchParams"
        @keyup.enter.native="handleTreeSearch"
      >
        <template slot="append">
          <el-button icon="el-icon-refresh" @click="resetSearch"></el-button>
        </template>
      </el-input>
      <div class="roll-dialog">
        <el-tree
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          :check-strictly="true"
          @check="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>
  </div>
</template>

<script>
import {
  isHead,
  findCustListByGroupId,
  campaignDetail,
  customerAppoint,
} from "@/api/system/findCustByGroupId.js";
import { getDeptTree, getDeptUserTree } from "@/api/grid/address/tree.js";
import { Message } from "element-ui";
export default {
  data() {
    return {
      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 },
        // { key: 7, label: `分群名称`, visible: true },
      ],
      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: "801000",
      selectedIds: [],
      executer: "",
      children: [],
      distributeType:0,
      groupType: "",
      isorgName: true,
      isgridName: false,
      isuserName: false,
      isbranch: false,
      isHead: false,
      defaultDeptProps: {
        children: "children",
        label: "label",
        disabled: (data) =>
          !["head", "branch", "outlet", "user"].includes(data.level),
      },
    };
  },
  computed: {
    paginatedData() {
      const start = (this.pageNum - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.custTableData.slice(start, end);
    },
  },

  mounted() {
    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'})
    const id = this.$route.query.groupId;
    this.groupId = id;
    const groupType = this.$route.query.groupType;
    this.groupType = groupType;
    const campaignId = this.$route.query.campaignId;
    // console.log(groupType);
    this.campaignId = campaignId;
    campaignDetail({ 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(id, this.pageNum, this.pageSize, this.groupType);
  },
  methods: {
    // //判断当前用户登录身份
    // 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";
    //     } else if (Object.keys(res)[0].startsWith("b")) {
    //       this.radiosButonIsDisableFromMe = false;
    //       this.radiosButonIsDisableToMe = false;
    //       this.createRole = "1";
    //     } else if (
    //       Object.keys(res)[0].startsWith("m") ||
    //       this.$store.getters.roles[0] == "admin"
    //     ) {
    //       this.radiosButonIsDisableFromMe = false;
    //       this.radiosButonIsDisableToMe = false;
    //       this.createRole = "2";
    //     } else {
    //       this.radiosButonIsDisableFromMe = false;
    //       this.radiosButonIsDisableToMe = false;
    //     }
    //   });
    // },
    handleDialogCancle()  {
      this.$refs.groupCustomerDetail.clearSelection();
      this.dialogVisible = false;
      this.dialogVisible = false;
    },
    handlenodeClick(data) {
      console.log(data);
    },

    handleoneSend(row) {
      this.$refs.groupCustomerDetail.toggleRowSelection(row, true);
    },
    handleConfigeInfo() {
   
      if (this.isHead&&this.executer == 0) {
        customerAppoint({
          custIds: this.selectedIds.join(",")||this.custIds,
          deptIds: this.checkedKeys.join(","),
          groupId: this.groupId,
          campaignId: this.campaignId,
          createRole: this.createRole,
        }).then((res) => {
          // console.log(res);
          if (res.code == "200") {
            Message.success("推送成功");
            // alert(1)

            this.dialogVisible = false;
            this.selectedRows.map((item) => {
              return (item.pushStatus = "1");
            });
            this.$refs.groupCustomerDetail.clearSelection();
          }
        });
      }
      //推送到个人的情况
      else if (this.isHead&&this.executer == 1) {
        customerAppoint({
          custIds: this.selectedIds.join(",")||this.custIds,
          deptIds: "",
          userIds: this.userIds.join(","),
          groupId: this.groupId,
          campaignId: this.campaignId,
          createRole:this.createRole,
        }).then((res) => {
          // console.log(res);
          if (res.code == "200") {
            Message.success("推送成功");
            // alert(2)
            this.dialogVisible = false;
            this.selectedRows.map((item) => {
              return (item.pushStatus = "1");
            });
            this.$refs.groupCustomerDetail.clearSelection();
          }
        });
      }else if(this.isbranch==true) {
          customerAppoint({
          custIds: this.selectedIds.join(",")||this.custIds,
          deptIds: "",
          userIds: this.userIds.join(","),
          groupId: this.groupId,
          campaignId: this.campaignId,
          createRole: this.createRole,
        }).then((res) => {
          // console.log(res);
          if (res.code == "200") {
            Message.success("推送成功");
            // alert(3)
            this.dialogVisible = false;
            this.selectedRows.map((item) => {
              return (item.pushStatus = "1");
            });
            this.$refs.groupCustomerDetail.clearSelection();
          }
        });
      }
      else {
        customerAppoint({
          custIds: this.selectedIds.join(",")||this.custIds,
          deptIds: this.checkedKeys.join(","),
          userIds: this.userIds.join(","),
          groupId: this.groupId,
          campaignId: this.campaignId,
          createRole: this.createRole,
        }).then((res) => {
          // console.log(res);
          if (res.code == "200") {
            Message.success("推送成功");
                  //  alert(4)
            this.dialogVisible = false;
            this.selectedRows.map((item) => {
              return (item.pushStatus = "1");
            });
            this.$refs.groupCustomerDetail.clearSelection();
          }
        });
      }
    },
    exportDataByCustIds() {
      // console.log(this.selectedRows);
        if (this.selectedIds.length == 0) {
        Message.warning("请先选择导出客户");
        return;
      }
      const custIds = this.selectedRows.map((item) => {
        return (item = item.custId);
      });
      this.download(
        `/system/group/exportDataByCustIds/?groupId=${
          this.groupId
        }&custIds=${custIds.join(",")}`,
        {},
        `group_custIds_${new Date().getTime()}.xlsx`
      );
      this.$refs.groupCustomerDetail.clearSelection();
      Message.success('导出成功')
    },
    handleCheckChange(data) {
      console.log("this.executer======", this.executer,this.isbranch);
      //判断身份
      if(this.isbranch===true){
          // this.hasCheck = true;
            getDeptUserTree({ deptid: data.id }).then((res) => {
          // this.hasCheck = true;
          console.log("this.hasCheck======2", this.hasCheck);
          this.children = res;
          const tmp = this.children.map((item) => {
            return {
              key: item.userId,
              id: item.userId,
              label: item.userName,
              children: [],
              disabled: false,
              level: "user",
            };
          });
          data.children = tmp;
          this.$refs.deptTree.updateKeyChildren(data.id, tmp);
          // tmp.map(item => {
          //   const node = this.$refs.deptTree.getNode(item.key);
          this.$refs.deptTree.$on("check", (node, checked) => {
            // 在这里编写你的逻辑
            if (checked) {
              this.userIds.push(node.id);
              // this.checkedKeys = this.checkedKeys.map((item) => {
              //   return item != node.id;
              // });
              // console.log(this.checkedKeys);
            }
          });
          // })

          // this.hasCheck = true;
        });
          console.log('43234234');
          console.log("this.hasCheck======2", this.hasCheck);
          this.children = res;
          const tmp = this.children.map((item) => {
            return {
              key: item.userId,
              id: item.userId,
              label: item.userName,
              children: [],
              disabled: false,
              level: "user",
            };
          });
          data.children = tmp;
          this.$refs.deptTree.updateKeyChildren(data.id, tmp);
          // tmp.map(item => {
          //   const node = this.$refs.deptTree.getNode(item.key);
          this.$refs.deptTree.$on("check", (node, checked) => {
            // 在这里编写你的逻辑
            if (checked) {
              this.userIds.push(node.id);
              // this.checkedKeys = this.checkedKeys.map((item) => {
              //   return item != node.id;
              // });
              // console.log(this.checkedKeys);
            }
          });
          // })

          // this.hasCheck = true;
        
      }
      if (this.executer == "0") {
        this.checkedKeys = this.$refs.deptTree.getCheckedKeys();
      }
      // console.log(this.checkedKeys);
      if(this.isbranch&&this.executer) {
         // console.log("this.hasCheck======1", this.hasCheck);
        // // if (this.hasCheck) return;
        // console.log("1111111111111======");
        getDeptUserTree({ deptid: data.id }).then((res) => {
          // this.hasCheck = true;
          console.log("this.hasCheck======2", this.hasCheck);
          this.children = res;
          const tmp = this.children.map((item) => {
            return {
              key: item.userId,
              id: item.userId,
              label: item.userName,
              children: [],
              disabled: false,
              level: "user",
            };
          });
          data.children = tmp;
          this.$refs.deptTree.updateKeyChildren(data.id, tmp);
          // tmp.map(item => {
          //   const node = this.$refs.deptTree.getNode(item.key);
          this.$refs.deptTree.$on("check", (node, checked) => {
            // 在这里编写你的逻辑
            if (checked) {
              this.userIds.push(node.id);
              // this.checkedKeys = this.checkedKeys.map((item) => {
              //   return item != node.id;
              // });
              // console.log(this.checkedKeys);
            }
          });
          // })

          // this.hasCheck = true;
        });
      }
      if (this.executer == "1") {
        // console.log("this.hasCheck======1", this.hasCheck);
        // // if (this.hasCheck) return;
        // console.log("1111111111111======");
        getDeptUserTree({ deptid: data.id }).then((res) => {
          // this.hasCheck = true;
          console.log("this.hasCheck======2", this.hasCheck);
          this.children = res;
          const tmp = this.children.map((item) => {
            return {
              key: item.userId,
              id: item.userId,
              label: item.userName,
              children: [],
              disabled: false,
              level: "user",
            };
          });
          data.children = tmp;
          this.$refs.deptTree.updateKeyChildren(data.id, tmp);
          // tmp.map(item => {
          //   const node = this.$refs.deptTree.getNode(item.key);
          this.$refs.deptTree.$on("check", (node, checked) => {
            // 在这里编写你的逻辑
            if (checked) {
              this.userIds.push(node.id);
              // this.checkedKeys = this.checkedKeys.map((item) => {
              //   return item != node.id;
              // });
              // console.log(this.checkedKeys);
            }
          });
          // })

          // this.hasCheck = true;
        });
      }

      if (this.executer == "2") {
        this.checkedKeys = this.$refs.deptTree.getCheckedKeys();
        console.log("this.checkkeys============", this.checkedKeys);
        getDeptUserTree({ deptid: data.id }).then((res) => {
          // this.hasCheck = true;
          this.children = res;
          const tmp = this.children.map((item) => {
            return {
              key: item.userId,
              id: item.userId,
              label: item.userName,
              children: [],
              disabled: false,
              level: "user",
            };
          });
          data.children = tmp;
          this.$refs.deptTree.updateKeyChildren(data.id, tmp);
          // tmp.map(item => {
          //   const node = this.$refs.deptTree.getNode(item.key);
          this.$refs.deptTree.$on("check", (node, checked) => {
            // 在这里编写你的逻辑
            if (checked) {
              this.userIds.push(node.id);
              this.checkedKeys = this.checkedKeys.filter((item) => {
                return item != node.id && item != undefined;
              });
              console.log(this.checkedKeys);
            }
          });
          // })

          // this.hasCheck = true;
        });
      }
    },
    resetSearch() {
      this.searchParams = "";
      this.getDeptTreeSelect();
    },
    handleTreeSearch() {
      this.filterTreeData = this.filterTree(
        this.deptOptions,
        this.searchParams
      );
      if (this.searchParams) {
        console.log(this.filterTreeData[0]);
        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;
    },
    getDeptTreeSelect() {
      getDeptTree().then((response) => {
        // console.log(response)
        this.deptOptions = response.data;
      });
    },
     handleCustAppointOne(custId) {
      // if(this.isbranch&& this.distributeType==null){
      //   Message.warning('请返回上一级，新建活动成功后才可指定推送！')
      //   this.$refs.groupCustomerDetail.clearSelection();
      //   return;
      // }
      // if(this.executer==null&&this.isHead==true&&!this.isbranch){
      //   Message.warning('请返回上一级，新建活动成功后才可指定推送！')
      //   this.$refs.groupCustomerDetail.clearSelection();
      //   return;
      // }
      this.dialogVisible = true;
      this.custIds=custId
      this.getDeptTreeSelect();
    },
    handleCustAppoint() {
      if (this.selectedIds.length == 0) {
        Message.warning("请先选择指定客户");
        return;
      }
      if(this.executer==null&&!isHead){
        Message.warning('请返回上一级，新建活动成功后才可指定推送！')
        this.$refs.groupCustomerDetail.clearSelection();
        return;
      }
      this.dialogVisible = true;
      this.getDeptTreeSelect();
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      const selectedCustIds = this.selectedRows.map((item) => item.custId);
      this.selectedIds = selectedCustIds;
    },
    returnLastPage() {
      this.type==0?
      this.$router.push({path:'/customer/customerbase/segmentation'}): this.$router.push({path:'/grid/visit/checklist'});
    },
    handleFilterClear() {
      this.pushStatus = "";
      this.custName = "";
      this.custId = "";
      this.getSelectCustomerData();
    },
    handleStatus(status) {
      switch (status) {
        case "0":
          return "未推送";
        case "1":
          return "推送成功";
        case "2":
          return "推送失败";
      }
    },
    // 分页
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      const id = this.$route.query.groupId;
      const groupType = this.$route.query.groupType;
      this.getCustomerDetail(id, groupType, this.currentPage, this.pageSize);
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      const id = this.$route.query.groupId;
      this.getCustomerDetail(
        id,
        this.currentPage,
        this.pageSize,
        this.groupType
      );
    },
    getCustomerDetail(id, pageNum, pageSize, groupType) {
      findCustListByGroupId({
        groupId: id,
        currentPage: pageNum,
        pageSize: pageSize,
        groupType: groupType,
      }).then((res) => {
        this.custTableData = res.rows;
        this.total = res.total;
      });
    },
    //筛选查询
    getSelectCustomerData() {
      findCustListByGroupId({
        groupId: this.groupId,
        custName: this.custName,
        pushStatus: this.pushStatus[0],
        custId: this.custId,
        groupType: this.groupType,
      }).then((res) => {
        this.custTableData = res.rows;
        this.total = res.total;
      });
    },
  },
};
</script>

<style scoped>
.roll-dialog {
  overflow: auto;
  height: 600px;
}
</style>