<template>
  <div>
    <el-row class="title">
      <el-col>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="showCreateDialog = true"
          >创建分群</el-button
        >
      </el-col>
      <el-col>
        <el-radio-group
          class="title"
          v-model="selectedTab"
          @change="handleTabChange"
        >
          <el-radio-button
            label="我创建的"
            :disabled="radiosButonIsDisableFromMe"
            >我创建的</el-radio-button
          >
          <el-radio-button
            label="推荐给我的"
            :disabled="radiosButonIsDisableToMe"
            >推荐给我的</el-radio-button
          >
        </el-radio-group>
      </el-col>
      <el-col style="display: flex">
        <el-input
          v-model="searchQuery"
          placeholder="输入分群名称"
          clearable
          @clear="handSearch"
          @keyup.enter.native="handSearch"
        ></el-input>
        <el-button icon="el-icon-search" @click="handSearch"></el-button>
      </el-col>
    </el-row>
    <el-dialog
      :visible.sync="showCreateDialog"
      title="怎样创建分群？"
      width="30%"
    >
      <div class="dialog-content">
        <el-row>
          <el-button>规则创建</el-button>

          <el-button type="primary" @click="handleImport">导入创建</el-button>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => {showCreateDialog = false;this.getList();this.campaignId=''}">取消</el-button>
      </span>
    </el-dialog>
    <div v-if="!isCreatePag">
       <right-toolbar :handSearch.sync="handSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      <el-table :data="paginatedData" style="width: 100%">
        <el-table-column prop="groupName" label="分群名称" sortable v-if="columns[0].visible"></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="createType" label="创建方式" sortable  v-if="columns[3].visible"></el-table-column>
        <el-table-column prop="createBy" label="创建者" sortable  v-if="columns[4].visible"></el-table-column>
        <el-table-column prop="updateType" label="更新方法" sortable  v-if="columns[5].visible"></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"
        ></el-table-column>
        <el-table-column prop="operate" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="
                handleCustDetail(
                  scope.row.groupId,
                  scope.row.groupName,
                  scope.row.campaignId,
                  scope.row.groupType,
                  '0',
                  scope.row.distributeType
                )
              "
              >查看</el-button
            >
            <!-- <a href="#" @click.prevent="importIn">导入</a> -->
            <el-button
              type="text"
              @click="handleGroupCustExport(scope.row.groupId)"
              >导出</el-button
            >
            <!-- <a href="#" @click.prevent="recommend">推荐</a> -->
            <el-button
              type="text"
              :disabled="isHeader&&scope.row.createRole==1?true:false"
              @click="
                handlePushGroupCustomer(
                  scope.row.groupName,
                  scope.row.groupId,
                  scope.row.campaignId
                )
              "
              >推送</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <!-- 分页 -->
        <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="groupTable.length"
          :current-page="currentPage"
        ></el-pagination>
      </el-row>
    </div>
    <el-empty v-if="showmap" description="总行管理员无需推荐..." />
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="pushTitle"
      :visible.sync="pushOpen"
      width="600px"
      append-to-body
    >
      <el-form
        ref="pushform"
        :model="pushform"
        :rules="pushroles"
        label-width="80px"
        :disabled="ispushformread"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="分群名称" prop="groupName">
              <el-input
                v-model="pushform.groupName"
                :disabled="true"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动名称" prop="campaignName">
              <el-input
                v-model="pushform.campaignName"

                placeholder="请输入活动名称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动类型" prop="campaignType" style="flex: 1">
              <el-select
                v-model="pushform.campaignType"
                placeholder="请选择活动类型"
                width="100%"
              >
                <el-option label="走访" value="走访"></el-option>
                <el-option label="电话" value="电话"></el-option>
                <el-option label="短信" value="短信"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="紧急程度"
              prop="campaignDegree"
              style="flex: 1"
            >
              <el-select
                v-model="pushform.campaignDegree"
                placeholder="请选择紧急程度"
              >
                <el-option label="高" value="高"></el-option>
                <el-option label="中" value="中"></el-option>
                <el-option label="低" value="低"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="认领类型" prop="claimType" style="flex: 1">
              <el-select
                v-model="pushform.claimType"
                placeholder="请选择认领类型"
                width="100%"
              >
                <el-option label="强制认领" value="0"></el-option>
                <el-option label="可选认领" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- 活动时间 -->
          <el-col :span="24">
            <el-form-item label="活动时间" prop="dateRange" style="flex: 1">
              <el-date-picker
                width="100%"
                v-model="pushform.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="认领时间"
              prop="claimdateRange"
              style="flex: 1"
            >
              <el-date-picker
                width="100%"
                v-model="pushform.claimdateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="执行人" prop="executer" v-if="isHeader" style="flex: 1">
              <el-radio-group v-model="pushform.executer" width="100%">
                <el-radio label="0">机构</el-radio>
                <el-radio label="1">个人</el-radio>
                <el-radio label="2">混合分配</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="分配规则"
              prop="distributeType"
              style="flex: 1"
            >
              <el-radio-group v-model="pushform.distributeType" width="100%">
                <el-radio label="0">手动指定</el-radio>
                <el-radio label="1">按照客户归属机构</el-radio>
                <el-radio label="2">按照地址归属</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="ispushformread" @click="handleInfoSubmit">确 定</el-button>
        <el-button
          @click="
            () => {
              this.pushOpen = false;
              this.getList()
            }
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { groupList, exportData } from "@/api/system/grouplist";
import { isHead, campaignDetail } from "@/api/system/findCustByGroupId.js";
import { campaignAdd } from "@/api/system/campaign.js";
import { Message } from "element-ui";
export default {
  data() {
    return {
      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: true, message: "请选择分配规则" }],
      },
      pushform: {
        groupName: "",
        claimType: "",
        campaignDegree: "",
        campaignType: "",
        campaignName: "",
        executer: {},
        distributeType: {},
        claimdateRange: [],
        dateRange: [],
      },
      pushOpen: false,
      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,
      // 总条数
      total: 0,
      selectedTab: "我创建的",
      searchQuery: "",
      showCreateDialog: false,
      selectedCreateType: "",
      isCreatePage: false,
      tableData: [],
      groupId: "",
      createRole: "",
      campaignId: "",
      ispushformread: false,
      pushformDetail: {},
    };
  },
  computed: {
    filteredTableData() {
      if (this.searchQuery) {
        return this.groupTable.filter((item) =>
          item.groupName.includes(this.searchQuery)
        );
      }
      return this.groupTable;
    },
  },
  created() {
    // this.$router.go(0)
    this.isUserType();
    this.getList();
  },
  mounted() {
    if (this.$router.query.refresh) {
      this.$router.go(0);
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.groupTable.slice(start, end);
    },
  },
  methods: {
    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.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;

          campaignAdd(queryParams).then((res) => {
            if (res.code == "200") {
              Message.success(`分群${this.pushform.groupName}活动创建成功!`);
              this.getList()
              this.pushOpen = false;
              //将执行人类型传给详情
              // this.$router.push({ path: '/groupBase/customerDetail', query: { executer:this.pushform.executer} })
            }
          });
        } else {
          console.error("新增失败", error);
        }
      });
    },
    handlePushGroupCustomer(groupName, groupId, campaignId) {
      // console.log(campaignId);
      this.getList()
      this.pushOpen = true;
      this.pushform.groupName = groupName;
      this.groupId = groupId;
      // this.campaignId = campaignId;
      if( campaignId===null) {
          this.$nextTick(()=> {
            this.$refs.pushform.resetFields()
          })
          
          // this.pushform={};
          this.pushform.groupName = groupName;
          // this.pushform.pushroles={};
          this.ispushformread = false;
          // return;
          // return;
          // this.pushform.campaignName ='';
          // this.pushform.campaignDegree = '';
          // this.pushform.campaignType ='';
          // this.pushform.executer = '';
          // this.pushform.distributeType = '';
          // this.pushform.claimType = '';
          // this.pushform.dateRange = [];
          // this.pushform.claimdateRange = [];
      }else{
 campaignDetail({ campaignId: campaignId}).then((res) => {
        this.pushformDetail = res;
        if (this.campaignId!=null) {
          this.ispushformread = true;
          if (this.ispushformread) {
            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),
            ];
            }
         } 
        });
      
      }
       
    },
    handleGroupCustExport(groupId) {
      this.download(
        `/system/group/exportData/?groupId=${groupId}`,
        {},
        `group_customer_${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) {
      if(campaignId==null) {
       Message.warning('请先新建活动！')
       return;
      }
      this.$router.push({
        path: "/groupBase/customerDetail",
        query: { groupId, groupName, campaignId, groupType,type,distributeType },
      });
    },
    //处理搜索
    handSearch() {
      groupList({
        groupType: this.groupFlag,
        groupName: this.searchQuery,
      }).then((res) => {
        this.groupTable = res.rows;
        this.total = this.groupTable.length;
      });
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    getList() {
      groupList({ groupType: this.groupFlag }).then((res) => {
        this.groupTable = res.rows;
        this.total = this.groupTable.length;
      });
    },
    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" });
    },
    handleDialoClose() {
      this.showCreateDialog = false;
    },
    goBackToCreateType() {
      this.isCreatePage = false;
      this.showCreateDialog = true;
    },
  },
  mounted() {
    //初始化表格数据
    this.handleTabChange();
  },
};
</script>

<style scoped>
.title {
  display: flex;
  align-items: center;
  padding: 20px;
}

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

a {
  color: blue;
  margin: 5px;
}

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