import React, { Component } from "react";
import { connect } from "react-redux";
import { View } from "@tarojs/components";
import { AtSteps, AtButton } from "taro-ui";

import "taro-ui/dist/style/components/steps.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/tabs.scss";

import UserFloatingLayer from "../../components/common/userFloatingLayer";

import { add, minus, asyncAdd } from "../../actions/counter";
import Enterprise from "./enterprise";
import PublicContent from "./publicContent";
import Result from "./result";

import "./index.less";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import MessageNoticebar from "../../components/common/messageNoticebar";
import InterviewCustomer from "../../pages/interview/index";

const items = [
  { title: "选择公出企业" },
  { title: "填写公出内容" },
  { title: "提交公出审核" },
];

@connect(
  ({ counter }) => ({
    counter,
  }),
  (dispatch) => ({
    add() {
      dispatch(add());
    },
    dec() {
      dispatch(minus());
    },
    asyncAdd() {
      dispatch(asyncAdd());
    },
  })
)
class ApplyDepart extends Component {

  $instance = getCurrentInstance();

  constructor(props) {
    super(props);
    this.state = {
      current: 0,
      enterpriseInfor: {},
      selectArrderLocation: {},
      resultState: 0,
      resultId: "",
      punchClockInfor: {},
      // colors: "primary",
      // color: "secondary",
      // selectColor: 0,
      type: 0,
      isShow: false,
      tipList: [],

      // 需要面谈的客户列表，只有业务员自己的客户才能面谈
      interviewCustomerList: [],
      interviewIdx: 0,
      // 面谈后返回的id
      uaiIdList: [],

      refreshInterview: false
    };
  }

  componentDidShow() {
    const publicInfo = Taro.getStorageSync('publicInfo');
    if (!!publicInfo) {
      const { type, customerList, orderNo, contractNo } = publicInfo;
      const ids = customerList.map(item => item.id).join(',');
      const names = customerList.map(item => item.name).join(',');

      let enterpriseInfor = { type, id: ids, name: names };
      if (type === 1) {
        enterpriseInfor.orderNo = orderNo;
        enterpriseInfor.contractNo = contractNo;
      }

      this.setState({
        type,
        interviewCustomerList: type === 0 ? customerList : [],
        interviewIdx: 0,
        current: 1,
        enterpriseInfor,
        refreshInterview: type === 0 ? true : false,
      }, () => {
        Taro.removeStorageSync('publicInfo');
        this.setState({ refreshInterview: false });
      });
    }

    Taro.eventCenter.on("enterprise", (arg) => {
      arg.type = this.state.type;
      // 跳转
      this.setState({
        current: 1,
        enterpriseInfor: arg,
        // interviewCustomerList: arg.list.filter(item => item.myUser === 1),
        interviewCustomerList: arg.list,
        interviewIdx: 0
      });
    });
    Taro.eventCenter.on("publicContent", (arg) => {
      this.setState({
        current: 2,
        resultState: arg.code,
        resultId: arg.data ? arg.data.id : "",
        punchClockInfor: arg.data || {},
        isShow: arg.isShow,
        tipList: arg?.list,
      });
    });
    Taro.eventCenter.on("enterpriseBack", () => {
      const { type, interviewCustomerList } = this.state;
      if (type == 0 && interviewCustomerList.length) {
        this.setState({ interviewIdx: interviewCustomerList.length - 1 });
      } else {
        this.setState({
          current: 0,
        });
      }
      
    });
    Taro.eventCenter.on("result", () => {
      this.setState({
        current: 0,
        enterpriseInfor: {},
        selectArrderLocation: {},
        resultState: 0,
        resultId: "",
        punchClockInfor: {},
        uaiIdList: []
      });
    });
    //获取地区选定数据
    const chooseLocation = requirePlugin("chooseLocation");
    const location = chooseLocation.getLocation();
    if (location) {
      this.setState({
        selectArrderLocation: location,
      });
    }
  }

  onReachBottom() {
    if (this.state.current === 0) {
      Taro.eventCenter.trigger("applyDepartSearchList");
    }
  }

  handleCustomerPrev() {
      let { interviewIdx } = this.state;
      if (interviewIdx == 0) {
          this.setState({ current: 0, interviewIdx: -1 });
      } else {
          interviewIdx -= 1;
          this.setState({ interviewIdx });
      }
  }

  handleCustomerNext({ uid, uaiId }) {
    let { interviewIdx, uaiIdList } = this.state;
    uaiIdList[interviewIdx] = {uid, uaiId};
    interviewIdx = interviewIdx + 1;
    
    this.setState({ interviewIdx, uaiIdList });
  }

  setTabDisabled(item) {
    let userInfo = Taro.getStorageSync('userInfor');
    // 角色为营销，并且岗位为营销只能业务公出
    if ([1,2].indexOf(item.type) > -1 && userInfo.type == 1 && userInfo.position == 1) {
      return true;
    }
    //其他不隐藏
    return false;
  }

  render() {
    const { interviewCustomerList, interviewIdx } = this.state;
    return (
      <View className="applyDepart">
        <MessageNoticebar />
        <UserFloatingLayer />
        <View className="atStepsContent">
          <AtSteps items={items} current={this.state.current} />
          <View
            style={{ display: this.state.current === 0 ? "block" : "none" }}
          >
            <View style={{ display: "flex", padding: "0 5px" }}>
              {[
                { type: 0, title: "业务公出" },
                { type: 1, title: "技术公出" },
                { type: 2, title: "行政公出" },
                { type: 5, title: "非公出协单" },
              ].map((item, index) => (
                <View style={{ margin: "0 5px" }} key={item.type}>
                  <AtButton
                    circle
                    size="small"
                    disabled={this.setTabDisabled(item)}
                    type={
                      this.state.type == item.type ? "primary" : "secondary"
                    }
                    onClick={() => {
                      this.setState({
                        type: item.type,
                        interviewCustomerList: [],
                        interviewIdx: 0
                      });
                    }}
                  >
                    {item.title}
                  </AtButton>
                </View>
              ))}
              <View style={{ flex: "1" }}></View>
            </View>
          </View>
          <View className="content">
            <View
              style={{ display: this.state.current === 0 ? "block" : "none" }}
            >
              <Enterprise type={this.state.type} />
            </View>
            <View
              style={{ display: this.state.current === 1 ? "block" : "none" }}
            >
                {
                    this.state.type == 0 && interviewCustomerList.length && interviewIdx < interviewCustomerList.length && interviewIdx > -1 ? (
                      <InterviewCustomer
                        interviewIdx={interviewIdx}
                        customerList={interviewCustomerList}
                        uaiIdList={this.state.uaiIdList}
                        refreshInterview={this.state.refreshInterview}
                        onPrevClick={this.handleCustomerPrev.bind(this)}
                        onNextClick={this.handleCustomerNext.bind(this)}
                      />
                    ) : (
                      <PublicContent
                        enterpriseInfor={this.state.enterpriseInfor}
                        selectArrderLocation={this.state.selectArrderLocation}
                        uaiIdList={this.state.uaiIdList.map(item => item.uaiId)}
                      />
                    )
                }
         
            </View>
            <View
              style={{ display: this.state.current === 2 ? "block" : "none" }}
            >
              <Result
                resultState={this.state.resultState}
                resultId={this.state.resultId}
                punchClockInfor={this.state.punchClockInfor}
                isShow={this.state.isShow}
                tipList={this.state.tipList}
                type={this.state.type}
              />
            </View>
          </View>
        </View>
      </View>
    );
  }
}

export default ApplyDepart;
