import { doFetch, doFetchGet } from "@/components/axios/api";
import url from "@/components/axios/url";
import {
  checkFalse,
  checkSuccess
} from "../../../../../static/js/checkStatus";
import authMethods from "@/mixins/auth";
import defaultImg from "../../../../../static/img/default.png";
import { formatLongTime, paddingBorth } from "@/utils/utils";
import FreezeDialog from "../../components/dialog/freeze.vue";
import MemberFieldsDialog from "../../components/dialog/fieldsSettingDialog.vue";
import ExportFieldsDialog from "../../components/dialog/fieldsSettingDialog.vue";
export default {
  name: "abnormal-member-list",
  components: {
    ExportFieldsDialog,
    MemberFieldsDialog,
    FreezeDialog
  },
  mixins: [authMethods],
  filters: {
    formatBirth(value){
      return paddingBorth(value) || '--'
    },
    formatDate(val, format) {
      if (!val || val == -1) return format == "hms" ? "" : "--";
      let str = formatLongTime(val, 1);
      let arr = str.split(" ");
      if (format == "ymd") {
        return arr[0];
      } else if (format == "hms") {
        return arr[1] || "";
      }
      return str;
    }
  },
  data() {
    return {
      pickerOptions:{
        disabledDate(date){
          let minDate = new Date();
          minDate.setFullYear(minDate.getFullYear() - 1);
          minDate.setHours(0);
          minDate.setMinutes(0);
          minDate.setSeconds(0)

          let maxDate = new Date();
          maxDate.setHours(23);
          maxDate.setMinutes(59);
          maxDate.setSeconds(59)
          return date > maxDate || date < minDate;
        }
      },
      dateValue: ['',''],
      freezeDialogOptions: {
        count: 1,
        isBatchFreeze: 0,
        visible: false
      },
      exportData: {
        projectName: "member", // 当前项目名
        dialogVisible: false,
        type: 1,
        excelUrl: url.exceptionMemberExportExcel, // 下载数据的地址
        params: {} // 传递的参数
      },
      dialogMemberFieldVisible: false,
      dialogExportFieldVisible: false,
      defaultImg,
      settingType: 0, // 0未查询 1已设置 2未设置
      selectPage: {
        type: 0,
        dataReady: true
      },
      autoFrozen: 1,
      searchData: {
        memberCardStatus: "", //会员状态
        phoneNameCard: "", // 搜索字段
        pageName: "wxOpenCarMember",
        pageSize: 20,
        currentPage: 1,
        sortColName: "", // 排序字段
        sortType: "", // 排序方式
        showFields: "-1"
      },
      load: false,
      total: 0,
      memberFields: [], // 顶部标题配置
      exportFields: [], // 导出顶部配置
      list: [],
      multipleList: [],

      abnormalSettingSave: 0
    };
  },

  beforeMount() {
    this.init();
  },
  watch: {
    dateValue:{
      handler(value){
        value = value || ['',''];
        if(value[0] && value[1]){
          this.searchData.startDate = +value[0];
          this.searchData.endDate = +value[1];
        }else{
          this.searchData.startDate = '';
          this.searchData.endDate = '';
        }
      }
    },
  },
  activated(){
    this.init();
  },
  methods: {
    init() {
      this.getSetting().then(res => {
        this.settingType = res;
        if (res != 1) {
          return;
        }
        this.load = true;
        this.getFindMemberFields(this.searchData.pageName)
          .then(list => {
            this.memberFields = list;
            this.getList();
          })
          .catch(() => {
            this.getList();
          });
      });
    },
    getSetting() {
      return new Promise(resolve => {
        doFetchGet(url.getAbnormalSetting)
          .then(res => {
            let { errorCode, result, message } = res.data || {};
            if (errorCode != 0) {
              resolve(1);
              checkFalse(message);
              return;
            }
            if (result && result.configs) {
              let { exceptionRate, updateTime,frozen,calculateDate } = result;
              this.autoFrozen = frozen;
              if (updateTime > calculateDate) {
                // 配置更新时间大于数据更新时间 则数据还未刷新
                resolve(3);
              } else if (exceptionRate > 3) {
                resolve(4);
              } else {
                resolve(1);
              }
            } else {
              resolve(2);
            }
            this.updateData(result);
          })
          .catch(() => {
            resolve(1);
          });
      });
    },
    getFindMemberFields(pageName) {
      return new Promise((resolve, reject) => {
        if (!pageName) {
          reject();
        }
        doFetch(url.findMemberFields, {
          pageName
        })
          .then(res => {
            let { errorCode, result } = res.data;
            if (errorCode === 0 && Array.isArray(result)) {
              resolve(result || []);
            } else {
              checkFalse(res.data.message);
              reject(res);
            }
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    getList() {
      this.load = true;
      this.selectPage.dataReady = false;
      doFetchGet(url.getExceptionMemberList, this.searchData)
        .then(res => {
          this.selectPage.dataReady = true;
          this.load = false;
          let { errorCode, result } = res.data || {};
          if (errorCode === 0) {
            let { page, fields, fieldsStr } = result || {};
            let { result: list, totalCount } = page || {};
            list = list || [];
            list.forEach((item)=>{
              item.exceptionReasonList = (item.exceptionReason||'').split(';');
            })
            this.list = list || [];
            this.total = totalCount || 0;
          }
        })
        .catch(() => {
          this.load = false;
          this.selectPage.dataReady = true;
        });
    },

    // 搜索选项改变时
    onSearchDataChange() {
      this.searchData.currentPage = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.searchData.currentPage = val;
      this.getList();
    },
    handleSizeChange(pageSize){
      this.searchData.pageSize = pageSize;
      if((this.searchData.currentPage - 1) * this.searchData.pageSize > this.total){
        this.searchData.currentPage = 1;
      }      
      this.getList();
    },
    dateRangeChange(){
      this.searchData.currentPage = 1;
      this.getList();
    },
    submitMemberFields(fields) {
      doFetch(url.updateFields, {
        pageName: this.searchData.pageName,
        fields
      }).then(res => {
        if (res.data.errorCode === 0) {
          checkSuccess();
          // 需要对选中字段排序
          this.init();
        } else {
          checkFalse(res.data.message);
        }
      });
    },
    // 导出选项选择完毕 点击确定
    submitExportFields(fields) {
      doFetch(url.updateFields, {
        pageName: "memberTag",
        fields
      });
      doFetch(url.getEnableDownload).then(res => {
        let { errorCode, result } = res.data;
        if (errorCode === 0 && result == 1) {
          this.exportData.type = 2;
        } else {
          this.exportData.type = 1;
        }
      });
      let { phoneNameCard, memberCardStatus,startDate,endDate } = this.searchData || {};
      this.exportData.params = {
        startDate,
        endDate,
        memberCardStatus,
        phoneNameCard,
        exportFields: fields
      };
      this.exportData.dialogVisible = true;
    },
    freezeConfim(options){
      options = options || {};
      this.freezeDialogOptions = options;
    },
    freezeDialogHidden(){
      this.freezeDialogOptions = {
        visible: false
      }
    },
    // 冻结
    freezeItem(item) {
      this.freezeConfim({
        count: 1,
        isBatchFreeze: 0,
        isAbnormalFreeze: true,
        visible: true,
        submit:(options)=>{
          doFetchGet(url.updateFrozen,{
            status: 1,
            memberId: item.memberId,
            frozenType: options.frozenType,
            remark: options.remark || ""
          }).then((res)=>{
            if (res.data.errorCode === 0){
              checkSuccess();
              this.init();
            }
          }).finally(() => {
            this.freezeDialogOptions = {
              visible: false
            };
          });
        }
      })
    },
    // 解冻
    unfreezeItem(item) {
      doFetchGet(url.updateFrozen,{
        status: 0,
        memberId: item.memberId
      }).then(res => {
        if (res.data.errorCode === 0) {
          this.$message({
            message: "解冻成功",
            type: "success"
          });
          this.$nextTick(_ => {
            this.getList();
          });
        }
      });
    },
    // 获取当前选中的异常会员中未冻结的会员数量
    getUnfreezeCount() {
      return new Promise((resolve, reject) => {
        let { selectPage, multipleList, searchData } = this;
        let {phoneNameCard,memberCardStatus,startDate,endDate} = searchData;
        if (memberCardStatus == 2) {
          resolve(0);
          return;
        }
        let data = {
          startDate,
          endDate,
          all: selectPage.type == 2 ? 1 : 0,
          memberIds: multipleList.map(item => {
            return item.memberId;
          }),
          phoneNameCard: selectPage.type == 2 ? phoneNameCard : ""
        };

        doFetch(url.getUnfreezeCount, data)
          .then(res => {
            let { errorCode, message, result } = res.data;
            if (errorCode === 0) {
              resolve(result || 0);
            } else {
              checkFalse(message);
              reject(res.data);
            }
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    // 批量冻结
    async clickBatchFreeze() {
      let { multipleList,list } = this;
      if(!(list && list.length)){
        this.$message({
          message: "暂无数据，无法冻结",
          type: "warning"
        });
        return;
      }
      if (!(multipleList && multipleList.length)) {
        return this.$message.warning("请勾选要修改的会员");
      }
      let count = await this.getUnfreezeCount();
      if (count) {
        this.freezeConfim({
          count: count,
          isBatchFreeze: 1,
          isAbnormalFreeze: true,
          visible: true,
          submit: this.batchFreeze
        })
        // this.freezeDialogOptions = {
        //   count: count,
        //   isBatchFreeze: 1,
        //   visible: true
        // };
      } else {
        this.$message.warning("当前勾选的会员都为冻结状态，请重新勾选");
      }
    },
    freezeStatusChangeSuccess(taskId) {
      this.$confirm(
        "任务发起成功，请去【企业管理】-【任务中心】查看处理结果和执行进度",
        "任务发起成功",
        {
          confirmButtonText: "去任务中心",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          customClass: "import-link-confirm-content",
          type: "warning"
        }
      )
        .then(() => {
          window.open(`/gic-web/#/taskDetail/${taskId}`);
          this.init();
        })
        .catch(() => {
          this.init();
        });
    },
    // 批量冻结
    batchFreeze(options) {
      let { selectPage, multipleList, searchData } = this;
      let {startDate,endDate,phoneNameCard} = searchData;
      let data = {
        startDate,
        endDate,
        phoneNameCard,
        all: selectPage.type == 2  ? 1 : 0,
        memberIds: multipleList.map(item => {
          return item.memberId;
        }),
        frozenType: options.frozenType,
        remark: options.remark || "",
      };
      doFetch(url.exceptionMemberBatchFrozen, data)
        .then(res => {
          if (res.data.errorCode === 0) {
            this.freezeStatusChangeSuccess(res.data.result);
          }
        })
        .finally(() => {
          this.freezeDialogHidden();
        });
    },
    // 搜索结果导出
    download() {
      if (this.total) {
        this.getFindMemberFields("memberTag").then(list => {
          this.exportFields = list;
          this.dialogExportFieldVisible = true;
        });
      } else {
        this.$message.warning("暂无数据，无法导出");
      }
    },
    // 去配置
    toSettingPage() {
      if(!this.getCodeAuth('memberAbnormalSetting')) {
        this.$message.warning("无“异常规则配置”权限");
        return;
      }
      this.$router.push({
        path: "/abnormal-setting"
      });
    },
    linkDetail(memberId) {
      if (!this.getCodeAuth("memberIntoCustomDetail")) return;
      this.$router.push({
        path: "/customerDetail",
        query: { memberId }
      });
    }
  }
};
