import NavPath from "@/common/navbar/navbar.vue";
import tableColumDailog from "./components/tableColumDialog.vue";
import integralDailog from "./components/integralDialog.vue";
import gradeDailog from "./components/batchgradeDialog.vue";
import mainstoreDailog from "./components/mainstoreDialog.vue";
import substoreDailog from "./components/substoreDialog.vue";
import batchList from "./components/batchList.vue";
import importDialog from "./components/importDialog.vue";
import { doFetch, doFetchGet } from "../../components/axios/api";
import url from "../../components/axios/url";
import { mapState } from "vuex";
import { formatLongTime, paddingBorth } from "@/utils/utils";
import defaultImg from "../../../static/img/default.png";
import authMethods from "@/mixins/auth";
import {
  checkFalse,
  checkStatus,
  checkSuccess
} from "../../../static/js/checkStatus";
export default {
  name: "allCustomersList",
  data() {
    return {
      selectChannelValue: '',
      selectChannelList: {
        selectOptions: {
          collapseTags: true,
          allCheckText: '全部关联渠道',
          placeholder: '全部关联渠道',
          width: 200
        },
        treeOptions: {
          data: [
        // {
        //   id: '1',
        //   label: '微信公众号',
        //   disabled: false
        // },
          ],
          props: {
            label: 'label',
            children: 'children',
            value: 'id'
          }
        },
        searchAble: false,
        multipleAble: true
    },
      sceneValue: "member", // 人群筛选器场景值
      navpath: [
        { name: "首页", path: "" },
        { name: "客户列表", path: "" },
        { name: "全部客户", path: "" }
      ],
      pageParam: {
        currentPage: 1,
        pageSize: 20,
        phoneNameCard: "", // 搜索字段
        memberSearchStr: -1, // 人群筛选
        sortColName: "", // 排序字段
        sortType: "", // 排序方式
      },
      totalCount: 0,
      loading: false,
      tableData: [],
      customerType: [
      ],
      channelType: [],
      oldCustomerType: "",
      showSearch: false, // 高级搜索开关
      toggleTag: false, // 人群筛选器按钮开关
      dialogFieldVisible: false, // 列表字段设置弹窗开关
      memberFields: [], // 列表字段
      checkedFields: [], // 已选列表字段
      memberFieldsName: {}, // 已选列表字段名称
      isExist: {}, // 该商户表中是否存在列表字段 判断是否支持排序
      multipleList: [],
      dialogIntegralVisible: false,
      dialogGradeVisible: false,
      dialogMainstoreVisible: false,
      dialogSubStoreVisible: false,
      dialogImportVisible: false,
      selectAll: false, // 列表全选开关
      batchValue: '',
      batchOpt: [
        // 批处理选项
        { value: "integral", label: "调整积分", code: "memberBatchSetIntegral" },
        { value: "grade", label: "修改等级", code: "memberBatchSetGrade" },
        { value: "mainstore", label: "修改服务门店", code: "memberBatchSetService" },
        { value: "store", label: "修改协管门店", code: "memberBatchSetCustomer" }
      ],
      defaultImg,
      integralFlag: "", // 积分调整权限
      memberGrade: [], // 商户等级列表
      cliqueMemberGrade: [], // 集团等级列表
      selectTreeOptions: {
        selectOptions: {
          collapseTags: false,
          allCheckText: '全部客户',
          placeholder: '全部客户',
          width: 240
        },
        treeOptions: {
          data: [
            {
              id: 1,
              label: "非会员",
              disabled: false
            },
            {
              id: 2,
              label: "会员",
              disabled: false,
              children: [
                {
                  id: 3,
                  label: "微信会员",
                  disabled: false
                },
                {
                  id: 4,
                  label: "POS会员",
                  disabled: false
                }
              ]
            }
          ],
          props: {
            label: 'label',
            children: 'children',
            value: 'id'
          }
        },
        searchAble: false,
        multipleAble: true
      },
      defaultProps: {
        children: "children",
        label: "label"
      }
    };
  },
  mixins: [authMethods],
  components: {
    NavPath,
    tableColumDailog,
    integralDailog,
    gradeDailog,
    mainstoreDailog,
    substoreDailog,
    importDialog,
    batchList
  },
  computed: {
    pageName: function() {
      // 1-非会员 notMember 3-微信会员 wxOpenCarMember 4-pos会员 posMember
      const filterObj = {
        1: "notMember",
        3: "wxOpenCarMember",
        4: "posMember"
      };
      const list = [];
      this.customerType.forEach(el => {
        list.push(filterObj[el.id]);
      });
      return list.length
        ? list.join(",")
        : "notMember,wxOpenCarMember,posMember";
    },
    selectObj: function() {
      return {
        selectAll: this.selectAll,
        multipleList: this.multipleList,
        totalCount: this.totalCount
      };
    },
    ajaxObj: function() {
      return { ...this.pageParam, pageName: this.pageName };
    },
    ...mapState(["storeImageUrl", "showEditClique"])
  },
  filters: {
    sexFilter: function(v) {
      switch (v) {
        case 1:
          return "男";
        case 2:
          return "女";
        default:
          return "--";
      }
    }
  },
  watch: {
    customerType: {
      handler(newV, oldV) {
        this.onSearch();
      },
      deep: true
    },
    channelType: {
      handler(newV, oldV) {
        this.onSearch();
      },
      deep: true
    },
    $route: function(n, o) {
      if (n.path === "/allCustomers") {
        this.$store.commit("mutations-slide", true);
      }
    }
  },
  created() {
    this.$store.commit("mutations-slide", true);
    this.initialize();
    this.getGradeList();
    this.getCliqueGradeList();
    this.getMemberSourceList();
  },
  mounted() {
    this.getFindMemberFields();
    this.getAjaxMembers();
    this.getEnterpriseInfo();
  },
  beforUpdate() {},
  methods: {
    onSelectTreeChange(data) {
      this.customerType = data;
    },
    // 关联渠道选中数据
    onSelectChannelChange(data) {
      this.channelType = data.map(item=>{
        return item.id
      });
    },
    initialize() {
      this.pageParam.phoneNameCard = sessionStorage.getItem("phoneNameCard")
        ? sessionStorage.getItem("phoneNameCard")
        : "";
      this.pageParam.currentPage = sessionStorage.getItem("currentPage")
        ? sessionStorage.getItem("currentPage")
        : 1;
    },
    handleCurrentChange(val) {
      this.pageParam.currentPage = val;
      sessionStorage.setItem("currentPage", val);
      this.getAjaxMembers();
    },
    handleSizeChange(val) {
      this.pageParam.pageSize = val;
      this.getAjaxMembers();
    },
    onSearch() {
      this.pageParam.currentPage = 1;
      if(this.channelType) {
          this.pageParam.relatedChannelSource=this.channelType
      }
      this.getAjaxMembers();
    },
    // 获取会员渠道列表
    getMemberSourceList() {
      doFetchGet(url.getMemberSourceList, {}).then(res=>{
        if (res.data.errorCode === 0 && res.data.result) {
          this.selectChannelList.treeOptions.data = res.data.result.map(item=>{
            return {
              id: item.key,
              label: item.value,
              disabled: false
            }
          })
        }
      })
    },
    // 获取列表数据
    getAjaxMembers() {
      this.loading = true;
      this.selectAll = false;
      doFetch(
        url.ajaxMembers,
        Object.assign({}, this.pageParam, {
          pageName: this.pageName,
          showFields: "-1",
        })
      )
        .then(res => {
          this.loading = false;
          if (res.data.errorCode === 0 && res.data.result) {
            this.checkedFields = res.data.result.fieldsStr
              ? res.data.result.fieldsStr.split(",")
              : [
                  "name",
                  "grade",
                  "status",
                  "channel",
                  "costAll",
                  "costTimes",
                  "lastCostTime",
                  "attentionDate"
                ];
            this.isExist = Object.assign({}, res.data.result.fields || {});
            // 首先先保存数据 某些品牌的数据返回的很慢
            const resultData = res.data.result.page
              ? res.data.result.page.result
              : [];
            let tableData = [];
            if (resultData.length) {
              tableData = resultData.map(ele => ({
                ...ele,
                avgNumber: ele.avgNumber.toFixed(2),
                lastCostTime:
                  ele.lastCostTime != -1
                    ? formatLongTime(ele.lastCostTime, 2)
                    : "--", // 最近消费时间
                createTime:
                  ele.createTime != -1
                    ? formatLongTime(ele.createTime, 1)
                    : "--", // 新增时间
                attentionDate:
                  ele.attentionDate != -1
                    ? formatLongTime(ele.attentionDate, 1)
                    : "--", // 关注时间
                cancelAttentionTime:
                  ele.cancelAttentionTime != -1
                    ? formatLongTime(ele.cancelAttentionTime, 1)
                    : "--", // 取关时间
                attentionTime:
                  ele.attentionTime != -1
                    ? formatLongTime(ele.attentionTime, 1)
                    : "--", // 关注时间
                crateCardDateString:
                  ele.crateCardDateString != -1
                    ? formatLongTime(ele.crateCardDateString, 1)
                    : "--", // 开卡
                birthdayMD:
                  ele.birthdayMD != 0 ? paddingBorth(ele.birthdayMD) : "--", // 生日补全
                sex: ele.sex == 0 ? "--" : ele.sex == 1 ? "男" : "女",
                age: ele.age ? ele.age : "--",
                cardNo: ele.cardNo ? ele.cardNo : "--",
                mainStoreName: ele.mainStoreName
                ? ele.mainStoreName
                : "--",
                thirdImgUrl: ele.thirdImgUrl
                  ? ele.thirdImgUrl
                  : this.storeImageUrl
              }));
            }
            this.pageParam.currentPage = res.data.result.page.currentPage;
            this.totalCount = res.data.result.page.totalCount;
            this.tableData = [].concat(tableData);
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        })
        .finally(_ => (this.loading = false));
    },
    getFindMemberFields() {
      doFetch(url.findMemberFields, {
        pageName: this.pageName
      })
        .then(res => {
          if (res.data.errorCode === 0 && Array.isArray(res.data.result)) {
            const tempArr = [].concat(res.data.result);
            const memberFields = [];
            const memberFieldsName = [];
            tempArr.forEach(item => {
              memberFieldsName[item.code] = item.name;
              memberFields.push(item);
            });
            this.memberFields = [].concat(memberFields);
            this.memberFieldsName = Object.assign({}, memberFieldsName);
            // this.$nextTick(_ => {
            // });
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    submitMemberFields(v) {
      const check = v.split(",");
      const sortFieds = this.memberFields.reduce((res, cur) => {
        if (check.includes(cur.code)) {
          res.push(cur.code);
        }
        return res;
      }, []);
      doFetch(url.updateFields, {
        pageName: this.pageName,
        fields: sortFieds.toString()
      })
        .then(res => {
          if (res.data.errorCode === 0) {
            checkSuccess();
            // 需要对选中字段排序
            this.checkedFields = sortFieds;
            this.getAjaxMembers();
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    // 处理table 全选事件
    handleSelectAlll(val) {
      if (!val.length) this.selectAll = false;
    },
    // 处理table select事件
    handleSelectionChange(val) {
      if (val.length !== this.pageParam.pageSize) this.selectAll = false;
      this.multipleList = val;
    },
    // 处理table 排序事件
    sortChange(column, prop, order) {
      this.pageParam.sortColName = column.prop;
      if (column.order === "descending") {
        this.pageParam.sortType = "desc";
      }
      if (column.order === "ascending") {
        this.pageParam.sortType = "asc";
      }
      this.getAjaxMembers();
    },
    // 人群筛选器 - 校验与提交筛选结果
    getData() {
      this.$refs.peopleFilter.confirmSet();
    },
    // 人群筛选器 - 子组件触发父组件事件,返回过滤条件数据
    findFilter(value) {
      this.pageParam.memberSearchStr = !value ? -1 : value;
      this.onSearch();
    },
    // 人群筛选器 - 显示按钮
    editShow() {
      this.toggleTag = true;
    },
    // 人群筛选器 - 确认好选择条件之后 隐藏按钮
    editHide() {
      this.toggleTag = false;
    },
    // 人群筛选器 - 隐藏保存按钮和确认按钮  (子组件会调用)
    hideBtn(refresh) {
      if (refresh == 0) {
        this.pageParam.memberSearchStr = -1;
        this.getAjaxMembers();
        this.toggleTag = false;
      }
    },
    // 人群筛选器 - 取消人群筛选
    cancelFilter() {
      this.$refs.peopleFilter.cancelSet();
      this.toggleTag = false;
    },
    // 客户列表选择
    selectAllmultipleList() {
      this.selectAll = !this.selectAll;
      if (this.selectAll) {
        this.tableData.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 批量导入
    openDialogImport() {
      this.dialogImportVisible = true;
    },
    successImport(taskId, isImport) {
      // 不是批量导入，而且只选了一条数据时，不跳转到任务中心——炎羽
      if (!isImport && this.multipleList.length == 1) {
        // this.$message.success('修改完成');
        this.batchRefresh()
        return
      }
      this.$confirm(
        "任务发起成功，请去【系统】-【操作任务】-【任务中心】查看处理结果和执行进度",
        "任务发起成功",
        {
          confirmButtonText: "去任务中心",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          customClass: "import-link-confirm-content",
          type: "warning"
        }
      )
        .then(() => {
          window.open(`/gic-web/#/taskDetail/${taskId}`)
          this.batchRefresh()
        })
        .catch(() => {
          this.batchRefresh()
        });
    },
    // 批量处理
    handleFocusBatch(val) {
      if (this.multipleList.length < 1) {
        this.batchValue = "";
        checkFalse("请勾选会员");
        return false;
      }
      if (this.batchValue == "integral") {
        this.dialogIntegralVisible = true;
      } else if (this.batchValue == "grade") {
        this.dialogGradeVisible = true;
      } else if (this.batchValue == "mainstore") {
        this.dialogMainstoreVisible = true;
      } else if (this.batchValue == "store") {
        this.dialogSubStoreVisible = true;
      }
      this.batchValue = "";
    },
    // 批量导入修改
    batchImport() {
      this.openDialogImport();
    },
    batchRefresh() {
      this.getAjaxMembers();
    },
    getGradeList() {
      doFetch(url.gradeList)
        .then(res => {
          if (res.data.errorCode === 0) {
            this.memberGrade = res.data.result || [];
          } else {
            checkFalse(res.data.message);
            return false;
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    getCliqueGradeList() {
      doFetch(url.cliqueGradeList)
        .then(res => {
          if (res.data.errorCode === 0) {
            this.cliqueMemberGrade = res.data.result || [];
          } else {
            checkFalse(res.data.message);
            return false;
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    linkDetail(memberId) {
      if (!this.getCodeAuth('memberIntoCustomDetail')) return;
      this.$router.push({
        path: "/customerDetail",
        query: { memberId }
      });
    },
    getEnterpriseInfo() {
      doFetch(url.enterpriseInfo)
        .then(res => {
          if (res.data.errorCode == 0) {
            this.integralFlag = res.data.result.enterpriseInfo.integralFlag;
          } else {
            checkFalse();
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    }
  }
};
