import React, { Component } from "react";
import { View, Button, Text, Picker, RadioGroup, Label, Radio } from "@tarojs/components";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import { getProvince } from '../../utils/tools/index'
import {
  AtSearchBar,
  AtTextarea,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtInput,
  AtIcon,
  AtButton,
  AtInputNumber
} from "taro-ui";
import Skeleton from "taro-skeleton";
import {
  queryByUidAll,
  getInterviewByPrdid,
  updateUser,
  getInterviewListByPage,
  addOneContact,
  findCustomerContacts,
  updateMainContact,
  limitUser,
  getBusinessProjectByName,
  addProject,
  queryProjectList,
  delProject
} from "../../utils/servers/servers";
import "./index.less";

import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/textarea.scss";
import "taro-ui/dist/style/components/modal.scss";
import "taro-ui/dist/style/components/timeline.scss";
import "taro-ui/dist/style/components/calendar.scss";
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/search-bar.scss";

import MessageNoticebar from "../../components/common/messageNoticebar";
import { industry, channelTypeList, yearList, addressList } from '../../utils/tools/config';
import { getChannel } from "../../utils/tools";
import Superior from "../../components/common/superior";
import CheckboxPicker from "../../components/common/CheckboxPicker";
import AddressPicker from "../../components/common/addressPicker"
import CustomerProjectSelect from '../../components/common/CustomerProjectSelect';
import InterviewHisList from "../../components/common/InterviewHisList";

class CustomerOtherProfile extends Component {
  $instance = getCurrentInstance();

  constructor(props) {
    super(props);
    this.state = {
      dtails: {
        interviewList: []
      },
      interactShow: false,
      interactShowType: '',
      interactTitle: '',
      interactList: [],
    };
    // this.update = this.update.bind(this);
  }

  componentDidMount() {
    this.queryByUidAll();
  }

  componentDidUpdate(prevProps) {
    const { interviewIdx, customerList } = this.props;
    if ((interviewIdx != prevProps.interviewIdx && interviewIdx >= 0 && interviewIdx < customerList.length)) {
      this.queryByUidAll();
    } else if (this.props.refreshInterview) {
      this.queryByUidAll();
    }
  }


  handlePrevClick() {
    this.props.onPrevClick();
  }

  handleNextClick() {
    this.onSaveAllData((resData) => {
      this.props.onNextClick(resData);
    })
  }

  // 获取面谈思路表
  getInterviewData() {
    const uid = this.props.customerList[this.props.interviewIdx].id
    getInterviewListByPage({ uid, pageNo: 1, pageSize: 9999 }).then(res => {
      // 是否在面谈中，表示本次面谈未结束
      let isInterviewIng = this.props.uaiIdList.some(item => item.uid == uid);
      const { list } = res.data;
      let earlyCommunication = '',
        customerDemand = '',
        interviewIdeas = '',
        interviewPurpose = '',
        interviewRecommend = '',
        interviewFeedback = '',
        followUpPlan = '';
      if (list.length) {
        if (!list[list.length - 1].prdid || isInterviewIng) {
          earlyCommunication = list[list.length - 1].earlyCommunication;
          customerDemand = list[list.length - 1].customerDemand;
          interviewIdeas = list[list.length - 1].interviewIdeas;
          interviewPurpose = list[list.length - 1].interviewPurpose;
          interviewRecommend = list[list.length - 1].interviewRecommend;
          interviewFeedback = list[list.length - 1].interviewFeedback;
          followUpPlan = list[list.length - 1].followUpPlan;
        }
      }

      let defaultDetailData = this.state.dtails || {};
      this.setState({
        dtails: {
          ...defaultDetailData,
          earlyCommunication,
          customerDemand,
          interviewIdeas,
          interviewPurpose,
          interviewRecommend,
          interviewFeedback,
          followUpPlan,
          interviewList: list.filter(item => !!item.prdid),
        }
      });
    })
  }

  // 客户档案详情
  queryByUidAll() {
    const id = this.props.customerList[this.props.interviewIdx].id;
    queryByUidAll(
      true,
      { id }
    )
      .then((v) => {
        if (v.error.length === 0) {
          let dtailsData = {
            ...v.data,
          }
          this.setState({
            dtails: { ...dtailsData }
          }, () => {
            this.getInterviewData();
          });
        } else {
          setTimeout(() => {
            Taro.navigateBack({
              delta: 1
            })
          }, 1800);
          Taro.showToast({
            title: v.error[0].message,
            icon: "none",
            duration: 1800,
          });
        }
      })
      .catch((err) => {
        Taro.showToast({ title: "系统错误,请稍后再试", icon: "none" });
      });
  }

  validParams(params) {
    const { dtails } = this.state;
    let flag = true;
    let message = '';

    if (dtails.newChannel === 0 && !params.earlyCommunication || (params.earlyCommunication && params.earlyCommunication.length < 20)) {
      message = '请输入客户的难处，并且在20字以上';
      flag = false;
    } else if (dtails.newChannel === 0 && !params.customerDemand || (params.customerDemand && params.customerDemand.length < 20)) {
      message = '请输入客户的需求，并且在20字以上';
      flag = false;
    } else if (!params.interviewIdeas || (params.interviewIdeas && params.interviewIdeas.length < 20)) {
      message = '请输入面谈思路，并且在20字以上';
      flag = false;
    } else if (!params.interviewPurpose || (params.interviewPurpose && params.interviewPurpose.length < 20)) {
      message = '请输入面谈达成的目的，并且在20字以上';
      flag = false;
    } else if (dtails.newChannel === 0 && !params.interviewRecommend || (params.interviewRecommend && params.interviewRecommend.length < 20)) {
      message = '请输入经理/上级面谈建议，并且在20字以上';
      flag = false;
    } else {
      if (this.state.dtails.interviewList.length) {
        if (!params.interviewFeedback || (params.interviewFeedback && params.interviewFeedback.length < 20)) {
          message = '请输入面谈后的反馈，并且在20字以上';
          flag = false;
        } else if (!params.followUpPlan || (params.followUpPlan && params.followUpPlan.length < 20)) {
          message = '请输入后续跟进计划，并且在20字以上';
          flag = false;
        }
      }
    }
    return { flag, message };
  }

  onSaveAllData(callback) {
    const { dtails } = this.state;

    let params = {
      id: dtails.id,
      uid: dtails.uid,
      locationProvince: dtails.locationProvince,
      locationProvinceName: dtails.locationProvinceName,
      locationCity: dtails.locationCity,
      locationCityName: dtails.locationCityName,
      locationArea: dtails.locationArea,
      locationAreaName: dtails.locationAreaName,
      type: 2, // 1、更新档案和面谈，0、只更新档案，2、只更新面谈
    };

    // 是否在面谈中，表示本次面谈未结束
    let curruaiIdList = this.props.uaiIdList.filter(item => item.uid == dtails.uid);
    if (curruaiIdList.length) {
      // 面谈编号
      params.uaiId = curruaiIdList[0].uaiId;
    }

    if (dtails.newChannel == 1) {
      // 渠道客户
      params = {
        ...params,
        channelType: dtails.channelType,
        enterpriseCount: dtails.enterpriseCount,
        channelIndicators: dtails.channelIndicators,
        interviewIdeas: dtails.interviewIdeas,
        interviewPurpose: dtails.interviewPurpose,
        interviewFeedback: dtails.interviewFeedback,
        followUpPlan: dtails.followUpPlan,
      };
    } else {
      params = {
        ...params,
        industry: dtails.industry,
        industryName: dtails.industryName,
        earlyCommunication: dtails.earlyCommunication,
        customerDemand: dtails.customerDemand,
        interviewIdeas: dtails.interviewIdeas,
        interviewPurpose: dtails.interviewPurpose,
        interviewRecommend: dtails.interviewRecommend,
        interviewFeedback: dtails.interviewFeedback,
        followUpPlan: dtails.followUpPlan,
        patentCount: dtails.patentCount,
        inventionPatentCount: dtails.inventionPatentCount,
        utilityModelCount: dtails.utilityModelCount,
        appearancePatentCount: dtails.appearancePatentCount,
        softwareWorksCount: dtails.softwareWorksCount,
        otherCount: dtails.otherCount,
        financialData: dtails.financialData,
        companyCount: dtails.companyCount,
        socialSecurityCount: dtails.socialSecurityCount,
        externalInvestCount: dtails.externalInvestCount,
        externalInvestIndustry: dtails.externalInvestIndustry,
        externalInvestIndustryName: dtails.externalInvestIndustryName,
        externalInvestId: dtails.externalInvestId,
        externalInvestName: dtails.externalInvestName,
        financialRevenue: dtails.financialRevenue,
        financialTax: dtails.financialTax,
        financialProperty: dtails.financialProperty,
        financialRd: dtails.financialRd,
        standard: dtails.standard,
        businessScope: dtails.businessScope,
      };
    }


    for (let key in params) {
      if (params[key] === undefined || params[key] === 'undefined' || params[key] === null || params[key] === 'null') {
        delete params[key];
      }
    }

    const { flag, message } = this.validParams(params);
    if (!flag) {
      Taro.showToast({
        title: message,
        icon: "none",
      });
      return;
    }

    updateUser(params).then((v) => {
      if (v.error.length === 0) {
        Taro.showToast({
          title: "修改成功",
        });

        callback && callback(v.data);
      } else {
        Taro.showToast({
          title: v.error[0].message,
          icon: "none",
        });
      }
    })
  }

  openInteractHis(type) {
    let interactTitle;
    let interactList = this.state.dtails.interviewList;
    switch (type) {
      case 'earlyCommunication':
        interactTitle = '客户的难处历史记录';
        break;
      case 'customerDemand':
        interactTitle = '客户的需求历史记录';
        break;
      case 'interviewIdeas':
        interactTitle = '面谈思路历史记录';
        break;
      case 'interviewPurpose':
        interactTitle = '面谈达成的目的历史记录';
        break;
      case 'interviewRecommend':
        interactTitle = '经理/上级面谈建议历史记录';
        break;
      case 'interviewFeedback':
        interactTitle = '面谈后反馈历史记录';
        interactList = interactList.slice(1, interactList.length);
        break;
      case 'followUpPlan':
        interactTitle = '后续跟进计划历史记录';
        interactList = interactList.slice(1, interactList.length);
        break;
      default:
        break;
    }
    this.setState({
      interactShow: true,
      interactShowType: type,
      interactTitle,
      interactList
    });
  }


  render() {
    const { dtails } = this.state;
    return (
      <View className="customerProfile">
        <MessageNoticebar />
        <View
          className="titleContent"
        >

          <View className="content">
            <View className="valueContent">
              <View className="title" style={{ margin: "14rpx 0 18rpx;" }}>企业面谈思路表</View>

              <View className="othersTips">
                <View>您正在面谈他人企业!</View>
                <View>企业名称：{dtails.nickname}</View>
              </View>

              {dtails.newChannel === 0 && (
                <>
                  <View className="item">
                    <View className="item-title">
                      <View>
                        客户的难处:
                        <Text className="titleTips">（20字以上）</Text>
                      </View>
                      <View>
                        {dtails.interviewList && dtails.interviewList.length ? (
                          <AtIcon value='clock' size='20' color='#1E90FF' onClick={() => this.openInteractHis('earlyCommunication')}></AtIcon>
                        ) : null}
                      </View>
                    </View>
                    <View className="item-value">
                      <AtTextarea
                        value={dtails.earlyCommunication || ''}
                        placeholder='请编写本次面谈客户难处~'
                        count={false}
                        maxLength={1000}
                        onChange={value => {
                          dtails.earlyCommunication = value;
                          this.setState({ dtails });
                        }}
                      />
                    </View>
                  </View>

                  <View className="item">
                    <View className="item-title">
                      <View>
                        客户的需求:
                        <Text className="titleTips">（20字以上）</Text>
                      </View>
                      <View>
                        {dtails.interviewList && dtails.interviewList.length ? (
                          <AtIcon value='clock' size='20' color='#1E90FF' onClick={() => this.openInteractHis('customerDemand')}></AtIcon>
                        ) : null}
                      </View>
                    </View>
                    <View className="item-value">
                      <AtTextarea
                        value={dtails.customerDemand || ''}
                        placeholder='请编写本次面谈客户需求~'
                        count={false}
                        maxLength={1000}
                        onChange={value => {
                          dtails.customerDemand = value;
                          this.setState({ dtails });
                        }}
                      />
                    </View>
                  </View>
                </>
              )}


              <View className="item">
                <View className="item-title">
                  <View>
                    面谈思路:
                    <Text className="titleTips">（20字以上）</Text>
                  </View>
                  <View>
                    {dtails.interviewList && dtails.interviewList.length ? (
                      <AtIcon value='clock' size='20' color='#1E90FF' onClick={() => this.openInteractHis('interviewIdeas')}></AtIcon>
                    ) : null}
                  </View>
                </View>
                <View className="item-value">
                  <AtTextarea
                    value={dtails.interviewIdeas || ''}
                    placeholder='请编写本次面谈客户思路~'
                    count={false}
                    maxLength={1000}
                    onChange={value => {
                      dtails.interviewIdeas = value;
                      this.setState({ dtails });
                    }}
                  />
                </View>
              </View>

              <View className="item">
                <View className="item-title">
                  <View>
                    面谈达成的目的:
                    <Text className="titleTips">（20字以上）</Text>
                  </View>
                  <View>
                    {dtails.interviewList && dtails.interviewList.length ? (
                      <AtIcon value='clock' size='20' color='#1E90FF' onClick={() => this.openInteractHis('interviewPurpose')}></AtIcon>
                    ) : null}
                  </View>
                </View>
                <View className="item-value">
                  <AtTextarea
                    value={dtails.interviewPurpose || ''}
                    placeholder='请编写本次面谈达成的目的~'
                    count={false}
                    maxLength={1000}
                    onChange={value => {
                      dtails.interviewPurpose = value;
                      this.setState({ dtails });
                    }}
                  />
                </View>
              </View>

              {dtails.newChannel === 0 && (
                <View className="item">
                  <View className="item-title">
                    <View>
                      经理/上级面谈建议:
                      <Text className="titleTips">（由经理/上级口述，本人整理，20字以上）</Text>
                    </View>
                    <View>
                      {dtails.interviewList && dtails.interviewList.length ? (
                        <AtIcon value='clock' size='20' color='#1E90FF' onClick={() => this.openInteractHis('interviewRecommend')}></AtIcon>
                      ) : null}
                    </View>
                  </View>
                  <View className="item-value">
                    <AtTextarea
                      value={dtails.interviewRecommend || ''}
                      placeholder='请编写本次面谈建议~'
                      count={false}
                      maxLength={1000}
                      onChange={value => {
                        dtails.interviewRecommend = value;
                        this.setState({ dtails });
                      }}
                    />
                  </View>
                </View>
              )}

              {dtails.interviewList && dtails.interviewList.length ? (
                <>
                  <View className="item">
                    <View className="item-title">
                      <View>
                        面谈后的反馈:
                          <Text className="titleTips">（20字以上）</Text>
                      </View>
                      <View>
                        {dtails.interviewList && dtails.interviewList.length > 1 ? (
                          <AtIcon value='clock' size='20' color='#1E90FF' onClick={() => this.openInteractHis('interviewFeedback')}></AtIcon>
                        ) : null}
                      </View>
                    </View>
                    <View className="item-value">
                      <AtTextarea
                        value={dtails.interviewFeedback || ''}
                        placeholder='请编写本次面谈后的反馈~'
                        count={false}
                        maxLength={1000}
                        onChange={value => {
                          dtails.interviewFeedback = value;
                          this.setState({ dtails });
                        }}
                      />
                    </View>
                  </View>

                  <View className="item">
                    <View className="item-title">
                      <View>
                        后续跟进计划:
                          <Text className="titleTips">（20字以上）</Text>
                      </View>
                      <View>
                        {dtails.interviewList && dtails.interviewList.length > 1 ? (
                          <AtIcon value='clock' size='20' color='#1E90FF' onClick={() => this.openInteractHis('followUpPlan')}></AtIcon>
                        ) : null}
                      </View>
                    </View>
                    <View className="item-value">
                      <AtTextarea
                        value={dtails.followUpPlan || ''}
                        placeholder='请编写后续跟进计划~'
                        count={false}
                        maxLength={1000}
                        onChange={value => {
                          dtails.followUpPlan = value;
                          this.setState({ dtails });
                        }}
                      />
                    </View>
                  </View>
                </>
              ) : null}

              <View style={{ display: 'flex', marginTop: '24rpx' }}>
                <AtButton type="secondary" circle onClick={this.handlePrevClick.bind(this)}>上一页</AtButton>
                <AtButton type="primary" circle onClick={this.handleNextClick.bind(this)}>下一页</AtButton>
              </View>
            </View>
          </View>
        </View>

        {/* 沟通情况历史记录 */}
        <InterviewHisList
          isOpened={this.state.interactShow}
          list={this.state.interactList}
          type={this.state.interactShowType}
          title={this.state.interactTitle}
          onClose={() => {
            this.setState({ interactShow: false })
          }}
        />
      </View>
    );
  }
}

export default CustomerOtherProfile;
