import Taro, { Component } from "@tarojs/taro";
import { AtTabs, AtTabsPane } from "taro-ui";
import ListView from "@/components/ListView";
import "taro-ui/dist/style/components/tabs.scss";
import { savePoint, updatePoint } from "@/services/common";
import {
  getCustomerDetail,
  getVisitRecord,
  getActivityList,
  getFollowRecord,
  addFollowRecord,
  commitCustomerInfo,
  getBuildingType
} from "@/services/person";
import { connect } from "@tarojs/redux";
import { transferImage } from "@/utils/tools";
import dayjs from "dayjs";
import WaterMask from "@/components/WaterMask";

import * as noticeType from "@/constants/common.js";
import "./index.scss";
import ActivityItem from "./item";

const maleImg = require("@/assets/person/male.png");
const femaleImg = require("@/assets/person/female.png");
const phoneImg = require("@/assets/person/phone.png");
const messageImg = require("@/assets/person/message.png");

@connect(({ user, city }) => ({ user, city }))
export default class myCustomer extends Taro.Component {
  config = {
    navigationBarTitleText: "我的客户"
  };

  state = {
    current: 0,
    recordId: undefined, // 埋点ID
    activityList: [],
    followVisible: false,
    baseVisible: false,
    followValue: "", //跟进内容
    desc: "", //客户描述
    selector: [],
    sexSelector: ["男", "女"],
    customerDetail: {},
    followRecord: [],
    visitRecord: [],
    baseInfo: {}, // 完善信息弹框数据
    hasMore: true,
    isEmpty: false,
    pageIndex: 1,
    hasMore2: true,
    isEmpty2: false,
    pageIndex2: 1,
    hasMore3: true,
    isEmpty3: false,
    pageIndex3: 1
  };

  componentWillUnmount() {
    const { recordId } = this.state;
    recordId && updatePoint(recordId);
  }

  handleClick(value) {
    this.setState({
      current: value
    });
    if (value == 1) {
      this.queryVisitRecord(1);
    } else if (value == 2) {
      this.setState({
        activityList: []
      });
      this.queryActivityList(1);
    } else if (value == 3) {
      this.queryFollowRecord(1);
    }
  }
  // 访问记录上拉加载下拉刷新
  onScrollToLower = async fn => {
    const { pageIndex } = this.state;
    this.queryVisitRecord(pageIndex + 1);
    fn && fn();
  };
  onPullDownRefresh = rest => {
    // debugger
    if (this.refreshing) return;
    this.refreshing = true;
    this.queryVisitRecord(1);
    rest && rest();
    this.refreshing = false;
  };
  // 活动信息上拉加载下拉刷新
  onScrollToLower2 = async fn => {
    const { pageIndex2 } = this.state;
    this.queryActivityList(pageIndex2 + 1);
    fn && fn();
  };
  onPullDownRefresh2 = rest => {
    // debugger
    if (this.refreshing) return;
    this.refreshing = true;
    this.queryActivityList(1);
    rest && rest();
    this.refreshing = false;
  };
  // 跟进记录上拉加载下拉刷新
  onScrollToLower3 = async fn => {
    const { pageIndex3 } = this.state;
    this.queryFollowRecord(pageIndex3 + 1);
    fn && fn();
  };
  onPullDownRefresh3 = rest => {
    // debugger
    if (this.refreshing) return;
    this.refreshing = true;
    this.queryFollowRecord(1);
    rest && rest();
    this.refreshing = false;
  };
  // 获取访问记录
  queryVisitRecord(pageNumber) {
    const { customerId } = this.$router.params;
    const payload = {
      pageNumber,
      pageSize: "10",
      customerId
    };
    getVisitRecord(payload).then(res => {
      const { records, list, total, current, pages } = res || {};
      const _list = records || list || [];
      const newList =
        current <= 1 ? _list : this.state.visitRecord.concat(_list);
      this.setState({
        visitRecord: newList,
        isEmpty: total == 0,
        hasMore: current < pages,
        pageIndex: current >= pages ? pages : current
      });
    });
  }
  // 获取活动信息
  queryActivityList(pageNumber) {
    const { customerId } = this.$router.params;
    const payload = {
      pageNumber,
      pageSize: "10",
      customerId
    };
    getActivityList(payload).then(res => {
      const { records, list, total, current, pages } = res || {};
      const _list = records || list || [];
      const newList =
        current <= 1 ? _list : this.state.activityList.concat(_list);
      this.setState({
        activityList: newList,
        isEmpty2: total == 0,
        hasMore2: current < pages,
        pageIndex2: current >= pages ? pages : current
      });
    });
  }
  // 获取跟进记录
  queryFollowRecord(pageNumber) {
    const { customerId } = this.$router.params;
    const payload = {
      pageNumber,
      pageSize: "10",
      customerId
    };
    getFollowRecord(payload).then(res => {
      const { records, list, total, current, pages } = res || {};
      const _list = records || list || [];
      const newList =
        current <= 1 ? _list : this.state.followRecord.concat(_list);
      this.setState({
        followRecord: newList,
        isEmpty3: total == 0,
        hasMore3: current < pages,
        pageIndex3: current >= pages ? pages : current
      });
    });
  }
  componentDidShow() {
    this.loadList();
  }
  loadList() {
    const { customerId } = this.$router.params;
    getCustomerDetail(customerId).then(res => {
      this.setState({
        customerDetail: res || {}
      });
    });
  }

  addFollow() {
    this.setState({
      followVisible: true
    });
  }

  followSaveBtn() {
    if (this.state.followValue == "") {
      Taro.showToast({
        title: "跟进内容不能为空",
        icon: "none"
      });
    } else {
      const { customerId } = this.$router.params;
      const params = {
        recordType: "添加跟进",
        recordContent: this.state.followValue,
        customerSex: this.state.customerDetail.sex,
        customerId
      };
      addFollowRecord(params)
        .then(res => {
          this.queryFollowRecord(1);
          Taro.showToast({
            title: "添加跟进成功",
            icon: "none"
          });
        })
        .catch(err => {
          Taro.showToast({
            title: "添加跟进失败",
            icon: "none"
          });
        });
      this.setState({
        followVisible: false,
        followValue: ""
      });
    }
  }
  followCancelBtn() {
    this.setState({
      followVisible: false,
      followValue: ""
    });
  }
  onTextareaChange(e) {
    this.setState({
      followValue: e.target.value
    });
  }
  renderFollowBox() {
    const { followValue } = this.state;
    return (
      <View className="mask">
        <View className="content">
          <View style="display:flex;justify-content: space-between;">
            <View style="font-size:14px;color:#666">跟进内容：</View>
            <Textarea
              className="textarea"
              value={followValue}
              onInput={this.onTextareaChange}
              maxLength={150}
              placeholder="不超过150字"
            />
          </View>
          <View className="bottom-btn">
            <View className="save" onClick={this.followSaveBtn}>
              保存
            </View>
            <View className="cancel" onClick={this.followCancelBtn}>
              取消
            </View>
          </View>
        </View>
      </View>
    );
  }
  perfectInformation() {
    const { customerDetail } = this.state;
    this.setState({
      baseVisible: true,
      baseInfo: customerDetail
    });
    getBuildingType(customerDetail.buildingId).then(res => {
      this.setState({
        selector: res || []
      });
    });
  }
  // 保存
  baseSaveBtn() {
    const { customerId } = this.$router.params;
    const { baseInfo } = this.state;
    commitCustomerInfo(customerId, baseInfo).then(res => {
      this.setState({
        customerDetail: res || {}
      });
      Taro.showToast({
        title: "完善信息成功",
        icon: "none"
      });
    });
    this.setState({
      baseVisible: false
    });
  }
  // 取消
  baseCancelBtn() {
    this.setState({
      baseVisible: false
    });
  }
  onNameChange(e) {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        name: e.target.value
      }
    });
  }
  onSexChange = e => {
    let sex = e.detail.value == "0" ? "1" : e.detail.value == "1" ? "2" : "";
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        sex
      }
    });
  };
  onManageTypeChange(e) {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        realtyManageType: e.target.value
      }
    });
  }
  onPriceRangeChange(e) {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        priceRange: e.target.value
      }
    });
  }
  onChange = e => {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        demandType: this.state.selector[e.detail.value].buildingTypeName
      }
    });
  };
  onBaseTextareaChange(e) {
    this.setState({
      baseInfo: {
        ...this.state.baseInfo,
        describe: e.target.value
      }
    });
  }
  // 拨打电话
  handleTelClick(customer, e) {
    e.stopPropagation();
    Taro.makePhoneCall({
      phoneNumber: customer.phone
    });
    const params = {
      recordType: "拨打电话",
      customerSex: customer.sex,
      customerId: customer.customerId
    };
    addFollowRecord(params).then(res => {
      this.queryFollowRecord(1);
    });
    this.setState({
      followVisible: false
    });
  }
  handleChatClick(item, e) {
    e.stopPropagation();
    const {
      user: {
        userInfo: {
          miniApp: { tpls },
          person: { personId, nickname, name }
        }
      }
    } = this.props;
    const tplId = (
      tpls.filter(
        x => x.tplType == noticeType.TPL_NOTICE && x.isSubscribe == true
      )[0] || {}
    ).tplId;
    wx.requestSubscribeMessage({
      tmplIds: [tplId],
      success(res) {},
      fail(res) {},
      complete() {
        Taro.navigateTo({
          url: `/pages/im/index?sendId=${personId}&sendName=${encodeURIComponent(
            name || nickname
          )}&receiverId=${item.personId}&receiverName=${encodeURIComponent(
            item.name || item.nickname
          )}`
        });
      }
    });
  }
  renderBaseBox() {
    const { baseInfo, desc, selector, sexSelector } = this.state;

    return (
      <View className="mask">
        <View className="base-con">
          <View className="con-item">
            <View style="font-size:14px;color:#666">姓名：</View>
            <Input
              className="input"
              value={baseInfo.name}
              onInput={this.onNameChange}
              placeholder=""
            />
          </View>
          <View className="con-item">
            <View style="font-size:14px;color:#666">性别：</View>
            <View className="con-picker">
              <View>
                <Picker
                  mode="selector"
                  range={sexSelector}
                  onChange={this.onSexChange}
                >
                  <View className="picker">
                    {baseInfo.sex == "1"
                      ? "男"
                      : baseInfo.sex == "2"
                      ? "女"
                      : "　"}
                  </View>
                </Picker>
              </View>
              <View className="right-icon"></View>
            </View>
          </View>
          <View className="con-item">
            <View style="font-size:14px;color:#666">物业类型：</View>
            <Input
              className="input"
              value={baseInfo.realtyManageType}
              onInput={this.onManageTypeChange}
              placeholder=""
            />
          </View>
          <View className="con-item">
            <View style="font-size:14px;color:#666">项目类型：</View>
            <View className="con-picker">
              <View>
                <Picker
                  mode="selector"
                  range={selector}
                  range-key="buildingTypeName"
                  onChange={this.onChange}
                >
                  <View className="picker">{baseInfo.demandType || "　"}</View>
                </Picker>
              </View>
              <View className="right-icon"></View>
            </View>
          </View>
          <View className="con-item">
            <View style="font-size:14px;color:#666">价格区间：</View>
            <Input
              className="input"
              value={baseInfo.priceRange}
              onInput={this.onPriceRangeChange}
              placeholder=""
            />
          </View>
          <View style="display:flex;justify-content: space-between;">
            <View style="font-size:14px;color:#666">客户描述：</View>
            <Textarea
              className="textarea"
              value={baseInfo.describe}
              onInput={this.onBaseTextareaChange}
              maxLength={150}
              placeholder=""
            />
          </View>
          <View className="bottom-btn">
            <View className="save" onClick={this.baseSaveBtn}>
              保存
            </View>
            <View className="cancel" onClick={this.baseCancelBtn}>
              取消
            </View>
          </View>
        </View>
      </View>
    );
  }

  render() {
    const tabList = [
      { title: "基本信息" },
      { title: "访问记录" },
      { title: "活动信息" },
      { title: "跟进记录" }
    ];
    const {
      customerDetail,
      visitRecord,
      activityList,
      followRecord,
      followVisible,
      baseVisible,
      isEmpty,
      hasMore,
      isEmpty2,
      hasMore2,
      isEmpty3,
      hasMore3
    } = this.state;

    const { user } = this.props;
    const { person = {} } = (user || {}).userInfo || {};
    const waterText = person.nickname;

    return (
      <View>
        {followVisible && this.renderFollowBox()}
        {baseVisible && this.renderBaseBox()}
        <View
          className="user_con"
          style=" margin: 0 20rpx 40rpx 20rpx; height:256rpx;box-shadow:0rpx 4rpx 12rpx 0rpx rgba(0,0,0,0.12); border-radius:12rpx;"
        >
          <Image
            className="bg"
            src={transferImage(
              "https://njcj.oss-cn-shanghai.aliyuncs.com/miniapp/images/shop/background.jpg"
            )}
          ></Image>

          <View className="water-mask-box">
            <WaterMask text={waterText} />
          </View>

          <Image
            className="user__left__headimg"
            src={
              transferImage(customerDetail.picture) ||
              require("@/assets/default-avatar.png")
            }
          />
          <View className="user__left__name">
            <View className="text">{customerDetail.name}</View>
            {customerDetail.sex == "1" && (
              <Image
                style="width:36rpx;height:38rpx;margin-left:10rpx"
                src={maleImg}
              />
            )}
            {customerDetail.sex == "2" && (
              <Image
                style="width:36rpx;height:36rpx;margin-left:10rpx"
                src={femaleImg}
              />
            )}
          </View>
          <View className="user__left__phone">
            {customerDetail.phone}
            <Image
              onClick={this.handleTelClick.bind(this, customerDetail)}
              style="width:36rpx;height:36rpx;margin-left:20rpx;background:rgba(255,219,179,0.2);padding: 14rpx;border-radius: 30rpx;"
              src={phoneImg}
            />
            <Image
              onClick={this.handleChatClick.bind(this, customerDetail)}
              style="width:36rpx;height:36rpx;margin-left:40rpx;background:rgba(255,219,179,0.2);padding: 14rpx;border-radius: 30rpx;"
              src={messageImg}
            />
          </View>
        </View>
        <AtTabs
          height="calc(100vh - 300rpx)"
          className="my-tab"
          current={this.state.current}
          tabList={tabList}
          onClick={this.handleClick.bind(this)}
        >
          <AtTabsPane current={this.state.current} index={0}>
            <View className="tab-pane1 pane">
              <View className="status">
                {customerDetail.status == 1
                  ? "报备"
                  : customerDetail.status == 2
                  ? "到访"
                  : customerDetail.status == 3
                  ? "认筹"
                  : "签约"}
              </View>
              <View className="base-item">
                意向项目：
                <View className="con">
                  {customerDetail.intention || "暂无"}
                </View>
              </View>
              <View className="base-item">
                物业类型：
                <View className="con">
                  {customerDetail.realtyManageType || "暂无"}
                </View>
              </View>
              <View className="base-item">
                项目类型：
                <View className="con">
                  {customerDetail.demandType || "暂无"}
                </View>
              </View>
              <View className="base-item">
                价格区间：
                <View className="con">
                  {customerDetail.priceRange || "暂无"}
                </View>
              </View>
              <View className="base-item">
                客户描述：
                <View className="con">{customerDetail.describe || "暂无"}</View>
              </View>
              <View className="btn-box">
                <View className="btn" onClick={this.addFollow}>
                  添加跟进
                </View>
                <View className="info-btn" onClick={this.perfectInformation}>
                  完善信息
                </View>
              </View>
            </View>
          </AtTabsPane>
          <AtTabsPane current={this.state.current} index={1}>
            <View className="tab-pane2 pane">
              <ListView
                className="wrap"
                style="height:calc(100vh - 300rpx)"
                needInit
                isEmpty={isEmpty}
                emptyText="暂无访问记录~"
                hasMore={hasMore}
                onPullDownRefresh={fn => this.onPullDownRefresh(fn)}
                onScrollToLower={fn => this.onScrollToLower(fn)}
              >
                <View className="list">
                  {visitRecord.length &&
                    visitRecord.map((item, index) => (
                      <View className="record-item" key={index + "follow"}>
                        <View className="title">
                          {item.activity}
                          {(item.activityName || item.buildingName) && (
                            <Text> : </Text>
                          )}
                          {item.activityName || item.buildingName || ""}
                        </View>
                        <View className="time">
                          {dayjs(item.visitTime).format(
                            "YYYY年MM月DD日 HH:mm:ss"
                          ) || "　"}
                        </View>
                      </View>
                    ))}
                  {!visitRecord.length && (
                    <View className="empty">
                      {/* <Image className="empty__img" mode="widthFix" src={emptyImg}></Image>
                  <View className="empty__text">暂无访问记录~</View> */}
                    </View>
                  )}
                </View>
              </ListView>
            </View>
          </AtTabsPane>
          <AtTabsPane current={this.state.current} index={2}>
            <View className="tab-pane3 pane">
              <ListView
                className="wrap"
                style="height:calc(100vh - 300rpx)"
                needInit
                isEmpty={isEmpty2}
                emptyText="暂无活动信息~"
                hasMore={hasMore2}
                onPullDownRefresh={fn => this.onPullDownRefresh2(fn)}
                onScrollToLower={fn => this.onScrollToLower2(fn)}
              >
                <View className="list">
                  {!activityList.length && (
                    <View className="empty">
                      {/* <Image className="empty__img" mode="widthFix" src={emptyImg}></Image>
                  <View className="empty__text">暂无活动信息~</View> */}
                    </View>
                  )}
                  {activityList.length &&
                    activityList.map(item => (
                      <ActivityItem
                        data={item}
                        key={item.id + "activity"}
                      ></ActivityItem>
                    ))}
                </View>
              </ListView>
            </View>
          </AtTabsPane>
          <AtTabsPane current={this.state.current} index={3}>
            <View>
              <ListView
                className="wrap"
                needInit
                style="height:calc(100vh - 510rpx);padding:10px 20px 20px 20px"
                isEmpty={isEmpty3}
                emptyText="暂无跟进记录~"
                hasMore={hasMore3}
                onPullDownRefresh={fn => this.onPullDownRefresh3(fn)}
                onScrollToLower={fn => this.onScrollToLower3(fn)}
              >
                <View className="list">
                  {followRecord.length &&
                    followRecord.map(item => (
                      <View key={item.followUpRecordId + "follow"}>
                        <View style=" display:flex;justify-content: space-between;align-items: center;color: #333;font-size: 34rpx; margin-bottom:24rpx;">
                          <View style=" display: flex;align-items: center;">
                            <View style="width:8px;height:8px;margin-right:20rpx;display:inline-block;background:rgba(246,182,29,1);border-radius: 50%;"></View>
                            {item.recordType}
                          </View>
                          <View
                            classNam="time"
                            style=" font-size: 26rpx;color: #999;"
                          >
                            {dayjs(item.createDate).format(
                              "YYYY年MM月DD日 HH:mm:ss"
                            ) || "　"}
                          </View>
                        </View>
                        {item.recordContent && (
                          <View style="font-size:28rpx;color:#666;padding-left:32rpx;margin-bottom:20rpx;">
                            {item.recordContent}
                          </View>
                        )}
                      </View>
                    ))}
                  {!followRecord.length && (
                    <View className="empty">
                      {/* <Image className="empty__img" mode="widthFix" src={emptyImg}></Image>
                  <View className="empty__text">暂无跟进记录~</View> */}
                    </View>
                  )}
                </View>
              </ListView>
              <View className="btn-box">
                <View className="btn" onClick={this.addFollow}>
                  添加跟进
                </View>
              </View>
            </View>
          </AtTabsPane>
        </AtTabs>
      </View>
    );
  }
}
