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: "forzenlist",
  components: {
    ExportFieldsDialog,
    MemberFieldsDialog,
    FreezeDialog
  },
  mixins: [authMethods],
  filters: {
    formatBirth(value){
      if(value == -1){
        return '--'
      }
      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 {
      freezeDialogOptions: {
        count: 1,
        isBatchFreeze: 0,
        visible: false
      },
      exportData: {
        projectName: "member", // 当前项目名
        dialogVisible: false,
        type: 1,
        excelUrl: url.frozenMemberExportExcel, // 下载数据的地址
        params: {} // 传递的参数
      },
      dialogMemberFieldVisible: false,
      dialogExportFieldVisible: false,
      defaultImg,
      settingType: 0, // 0未查询 1已设置 2未设置
      selectPage: {
        type: 0,
        dataReady: true
      },
      searchData: {
        frozenType: '', //会员状态
        phoneNameCard: "", // 搜索字段
        pageName: "wxOpenCarMember",
        pageSize: 20,
        currentPage: 1,
        sortColName: "", // 排序字段
        sortType: "", // 排序方式
      },
      load: false,
      total: 0,
      memberFields: [], // 顶部标题配置
      exportFields: [], // 导出顶部配置
      list: [],
      multipleList: [],

      abnormalSettingSave: 0
    };
  },
  beforeMount() {
    this.init();
  },
  activated(){
    this.init();
  },
  methods: {
    init() {
      this.load = true;
      this.getFindMemberFields(this.searchData.pageName)
        .then(list => {
          this.memberFields = list;
          this.getList();
        })
        .catch(() => {
          this.getList();
        });
    },
    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;
      doFetch(url.getFrozenList, this.searchData)
        .then(res => {
          this.selectPage.dataReady = true;
          this.load = false;
          let { errorCode, result } = res.data || {};
          if (errorCode === 0) {
            let { result: list, totalCount } = result || {};
            this.list = list || [];
            this.total = totalCount || 0;
          }
        })
        .catch(() => {
          this.load = false;
          this.selectPage.dataReady = true;
        });
    },
    sortChange(column) {
      let { prop, order } = column;
      this.searchData.sortColName = prop;
      if (order === "descending") {
        this.searchData.sortType = "desc";
      }
      if (order === "ascending") {
        this.searchData.sortType = "asc";
      }
      this.getList();
    },

    // 搜索选项改变时
    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();
    },
    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, frozenType } = this.searchData || {};
      this.exportData.params = {
        frozenType,
        phoneNameCard,
        exportFields: fields
      };
      this.exportData.dialogVisible = true;
    },
    freezeConfim(options){
      options = options || {};
      this.freezeDialogOptions = options;
    },
    freezeDialogHidden(){
      this.freezeDialogOptions = {
        visible: false
      }
    },
    // 解冻
    unfreezeItem(item) {
      doFetchGet(url.updateFrozen,{
        status: 0,
        pageType: 1,
        memberId: item.memberId
      }).then(res => {
        if (res.data.errorCode === 0) {
          this.$message({
            message: "解冻成功",
            type: "success"
          });
          this.$nextTick(_ => {
            this.getList();
          });
        }
      });
    },
    // 批量解冻
    async clickBatchUnfreeze() {
      let { multipleList,list } = this;
      if(!(list && list.length)){
        this.$message({
          message: "暂无数据，无法解冻",
          type: "warning"
        });
        return;
      }
      if (!(multipleList && multipleList.length)) {
        return this.$message.warning("请勾选要修改的会员");
      }

      this.$confirm("确定解冻?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.batchUnfreeze();
      });
    },
    batchUnfreeze(){
      let ids = [];
      let { selectPage, multipleList, searchData } = this;
      let { phoneNameCard } = searchData;
      multipleList.forEach(ele => {
        ids.push(ele.memberId);
      });
      const datas = {
        memberIds: ids.join(","), // 会员id
        remark: "", // 备注暂留
        //所有会员是2 当前是1 其他是0
        isCurrent: selectPage.type == 2 ? 2 : 1,
        status: 0, // 1 冻结 0 解冻
        phoneNameCard,
      };
      doFetch(url.batchUpdateFrozen, datas).then(async res => {
        let {errorCode,result} = res.data;
        if (errorCode === 0) {
          this.$message({
            message: "解冻成功",
            type: "success"
          });
          this.freezeStatusChangeSuccess(result);
        }
      });
    },

    freezeStatusChangeSuccess(taskId) {
      this.$confirm(
        "任务发起成功，请去【企业管理】-【任务中心】查看处理结果和执行进度",
        "任务发起成功",
        {
          confirmButtonText: "去任务中心",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          customClass: "import-link-confirm-content",
          type: "success"
        }
      )
        .then(() => {
          this.getList();
          window.open(`/gic-web/#/taskDetail/${taskId}`);
        })
        .catch(() => {
          this.getList();
        });
    },
    // 搜索结果导出
    download() {
      if(this.total > 50000){
        this.$message.warning("单次导出数量最多5万条");
        return;
      }else
      if (this.total) {
        this.getFindMemberFields("memberTag").then(list => {
          this.exportFields = list;
          this.dialogExportFieldVisible = true;
        });
      } else {
        this.$message.warning("无数据");
      }
    },
    linkDetail(memberId) {
      this.$router.push({
        path: "/customerDetail",
        query: { memberId }
      });
    },
    // 去冻结会员页
    toFrozenMember(){
      this.$router.push({
        path: "/frozenList/frozenMember",
      });
    },
    toWhiteList(){
      this.$router.push({
        path: "/frozenWhiteList",
      });
    },
  }
};
