import { doFetch } from "@/components/axios/api";
import url from "@/components/axios/url";
import { mapState } from "vuex";
import { 
  checkFalse,
  checkStatus,
  checkSuccess 
} from "../../../../static/js/checkStatus";
import authMethods from "@/mixins/auth";
import defaultImg from "../../../../static/img/default.png";
import { formatLongTime } from "@/utils/utils";
import tableColumDialog from './components/dialog/tableColumDialog.vue';
export default {
  name: "forzenlist",
  components: {
    tableColumDialog
  },
  mixins: [authMethods],
  filters: {
    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;
    },
    formatCardName(val) {
      if (val) {
        if (val.length > 10) {
          val = val.substr(0, 10) + "...";
        }
      }
      return val;
    },
    formatMember(val) {
      if (val) {
        if (val.length > 3) {
          val = val.substr(0, 3) + "...";
        }
      }
      return val;
    },
    formatPhone(value) {
      if (!value) {
        return "--";
      }
      if (value.length != 11) {
        return value;
      }
      return `${value.substr(0, 3)}****${value.substr(7, 4)}`;
    }
  },
  data() {
    return {
      dialogFieldVisible: false,
      defaultImg,
      settingType: 0,// 0未查询 1已设置 2未设置
      selectPage: {
        type: 0,
        dataReady: true
      },
      searchData: {
        // memberCardStatus: "", //会员状态
        phoneNameCard: "", // 搜索字段
        pageName: "notMember,wxOpenCarMember,posMember",
        pageSize: 20,
        currentPage: 1,
        sortColName: "", // 排序字段
        sortType: "", // 排序方式
        showFields: "-1",
        memberSearchStr: -1 // 人群筛选
      },
      load: false,
      total: 0,
      memberFields: [],// 顶部标题配置
      frozenList: [],
      multipleList: []
    };
  },
  computed: {
    ...mapState(["storeImageUrl"])
  },
  created() {
    if (!this.storeImageUrl) {
      this.$store.dispatch("getStorePicture");
    }
    if (JSON.parse(sessionStorage.getItem("frozenListSearchData"))) {
      this.searchData = JSON.parse(
        sessionStorage.getItem("frozenListSearchData")
      );
    }
  },
  beforeMount() {
    this.init();
  },
  watch: {
    searchData: {
      handler(newval) {
        sessionStorage.setItem("frozenListSearchData", JSON.stringify(newval));
      }
    },
    deep: true,
    immediate: true
  },
  methods: {
    init(){
      this.getSetting()
      .then(()=>{
        this.settingType = 1;
        return this.getFindMemberFields('notMember');
      })
      .then(()=>{
        this.getList();
      })
    },
    getSetting(){
      return new Promise((resolve,reject)=>{
        resolve({})
      })
    },
    getFindMemberFields(pageName) {
      return new Promise((resolve,reject)=>{
        this.load = true;
        doFetch(url.findMemberFields, {
          pageName: this.searchData.pageName,
        })
          .then(res => {
            let { errorCode, result } = res.data;
            if (errorCode === 0 && Array.isArray(result)) {
              this.memberFields = result || [];
              resolve();
            } else {
              checkFalse(res.data.message);
              reject();
            }
          })
          .catch(err => {
            checkStatus(err);
            reject();
          }).finally(()=>{
            this.load = false;
          });
      })
    },
    getList() {
      this.load = true;
      this.selectPage.dataReady = false;
      doFetch(url.ajaxMembers, this.searchData)
        .then(res => {
          this.selectPage.dataReady = true;
          let { errorCode, result } = res.data || {};
          if (errorCode === 0) {
            let { page, fields, fieldsStr } = result || {};
            let { result: list, totalCount } = page || {};
            this.frozenList = list || [];
            this.total = totalCount || 0;
            this.load = false;
          } else {
            this.load = false;
          }
        }).finally(_ => {
          this.loading = false; 
          this.selectPage.dataReady = true;
        });;
    },
    sortChange(column){
      console.log(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.getList();
    },
    handleCurrentChange(val) {
      this.searchData.currentPage = val;
      this.getList();
    },
    unfreezeItem(item){
      const datas = {
        memberIds: item.memberId, // 会员id
        remark: "", // 备注暂留
        //所有会员是2 当前是1 其他是0
        isCurrent: 1,
        status: frozenStatus == 1 ? 1 : 0, // 1 冻结 0 解冻
        phoneNameCard: item.cardNo||'', // 会员名称 手机号
      };
      doFetch(url.batchUpdateFrozen, datas)
      .then((res)=>{
        if (res.data.errorCode === 0) {
          this.$message({
            message: "解冻成功",
            type: "success"
          });
          this.$nextTick(_ => {
            this.getList();
          });
        }
      });
    },
    freezeItem(item){
      let {memberId} = item;
      this.$confirm(`确定冻结?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const datas = {
          memberIds: memberId, // 会员id
          remark: "", // 备注暂留
          //所有会员是2 当前是1 其他是0
          isCurrent: 1,
          status: 1, // 1 冻结 0 解冻
          phoneNameCard: item.cardNo||'', // 会员名称 手机号
        };
        return doFetch(url.batchUpdateFrozen, datas);
      }).then((res)=>{
        if (res.data.errorCode === 0) {
          this.$message({
            message: "冻结成功",
            type: "success"
          });
          this.$nextTick(_ => {
            this.getList();
          });
        }
      });
    },

    submitMemberFields(fields){
      console.log('submitMemberFields->',fields);
      // this.dialogFieldVisible = true;
      doFetch(url.updateFields, {
        pageName: this.searchData.pageName,
        fields
      })
        .then(res => {
          if (res.data.errorCode === 0) {
            checkSuccess();
            // 需要对选中字段排序
            this.init();
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        });
    },
    // 批量冻结
    batchFreeze(){
      let {multipleList} = this;
      if(!(multipleList && multipleList.length)){
        return this.$message.warning('请勾选要修改的商户');
      }
      
    },
    // 搜索结果导出
    download(){
      // let {clique,status,search,principalMobile,areaCode} = this.searchParams;
      // window.location.href = `/gic-enterprise-operation-web/enterprise_service/export?clique=${clique}&status=${status}&search=${search}&principalMobile=${principalMobile}&areaCode=${areaCode}`
    },
    // 去配置
    toSettingPage(){
      this.$router.push({
        path: "/abnormal-setting"
      });
    },
    linkDetail(memberId) {
      this.$router.push({
        path: "/customerDetail",
        query: { memberId }
      });
    }
  }
};
