import React, { Component } from "react";
import { View, Text, Icon } from "@tarojs/components";
import { getUserByName, getOrderByUid, checkUserArchives } from "../../utils/servers/servers";

import { AtSearchBar, AtPagination, AtListItem, AtIcon, AtButton } from "taro-ui";

import "taro-ui/dist/style/components/search-bar.scss";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/pagination.scss";
import "./index.less";

import ListBottomStart from "../../components/common/listBottomStart";

import Taro from "@tarojs/taro";

class Enterprise extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      list: [],
      listState: "NO_DATA",
      selectId: 0,
      pageNo: 1,
      listVisible: false,
      listValue: {},
      orderNo: [],
      visibles: true,
    };
    this.onChange = this.onChange.bind(this);
  }

  onChange(value, lv = true) {
    this.setState({
      value,
    });
    if (value.length < 2 && !lv) {
      Taro.showToast({ title: "最少输入两个字符", icon: "none" });
      return;
    }
    if (value.length < 4 && lv) {
      return;
    }
    this.getList(value);
  }

  componentWillUnmount() {
    this.setState({
      value: "",
      list: [],
      listState: "NO_DATA",
      selectId: 0,
      pageNo: 1,
      totalCount: 0,
    });
  }

  getByUid(val) {
    this.setState({
      listState: "LOADING",
    });
    getOrderByUid({
      uid: val.id,
    }).then((msg) => {
      if (msg.error.length === 0) {
        let data = msg.data;
        this.setState({
          listState: "NO_MORE_DATA",
          orderNo: data,
        });
      } else {
        Taro.showToast({ title: msg.error[0].message, icon: "none" });
        this.setState({
          listState: msg.error[0].field === "403" ? "NO_DATA" : "RELOAD",
        });
      }
    });
  }

  getList(value = this.state.value, pageNo = 1) {
    Taro.showLoading({ title: "加载中..." });
    this.setState({
      listState: "LOADING",
    });
    getUserByName({
      type: 1,
      name: value,
      pageNo: pageNo,
      pageSize: 10,
    })
      .then((msg) => {
        Taro.hideLoading();
        if (msg.error.length === 0) {
          if (msg.data.totalCount === 0) {
            this.setState({
              listState: "NO_DATA",
            });
          } else if (
            msg.data.totalCount === this.state.list.length &&
            pageNo !== 1
          ) {
            Taro.showToast({ title: "没有更多数据了", icon: "none" });
            this.setState({
              listState: "NO_MORE_DATA",
            });
          } else {
            if (
              msg.data.totalCount ===
              (pageNo === 1
                ? msg.data.list
                : this.state.list.concat(msg.data.list)
              ).length
            ) {
              this.setState({
                listState: "NO_MORE_DATA",
              });
            }
          }
          this.setState({
            list: msg.data.list,
            pageNo: msg.data.pageNo,
            totalCount: msg.data.totalCount,
          });
        } else {
          Taro.showToast({ title: msg.error[0].message, icon: "none" });
          this.setState({
            listState: msg.error[0].field === "403" ? "NO_DATA" : "RELOAD",
          });
        }
      })
      .catch(() => {
        Taro.hideLoading();
        this.setState({
          listState: "RELOAD",
        });
      });
  }

  checkUserArchives(v) {

    if (v.status == 2 && this.props.type == 0) {
      Taro.showToast({
        title: "请在“单位公共客户”中领取后，再次发起公出！",
        icon: 'none'
      })
      return
    }

    let list = this.props.newList
    for (var i = 0; i < list.length; i++) {
      if (list[i].id == v.id) {
        Taro.showToast({
          title: "该企业已在公出列表中",
          icon: 'none'
        })
        return
      }
    }

    if (this.props.type == 1 || this.props.type == 2) {
      list.push(v)
      this.setState({
        newList: list
      })
      return
    }

    checkUserArchives({
      uid: v.id
    })
      .then((msg) => {
        if (msg.error.length === 0) {
          if (msg.data) {
            list.push(v)
            this.setState({
              newList: list
            })
          } else {
            Taro.showToast({
              title: "请先完善客户档案，才可发起公出",
              icon: 'none'
            })
          }
        } else {
          Taro.showToast({
            title: msg.error[0].message,
            icon: "none",
          });
        }
      })
      .catch(() => {
        this.setState({
          listState: "RELOAD",
        });
      });
  }

  render() {
    return (
      <>
        <AtSearchBar
          showActionButton
          value={this.state.value}
          placeholder="请输入公出企业名称0"
          onChange={this.onChange}
          onActionClick={() => {
            this.onChange(this.state.value, false);
          }}
          onConfirm={() => {
            this.onChange(this.state.value, false);
          }}
          onClear={() => {
            this.setState(
              {
                value: "",
                list: [],
                orderNo: [],
                listValue: {},
                listVisible: false,
                listState: "NO_DATA",
                selectId: 0,
                pageNo: 1,
                totalCount: 0,
              },
              () => {
                this.props.onChange({}, 0);
              }
            );
          }}
        />
        {
          this.props.newList.length > 0 && this.props.type != 1 &&
          <View className="slist">
            <View style={{ fontSize: "30rpx" }}>本次公出列表</View>
            {
              this.props.newList.map((item, index) =>
                <View className="slitems" key={index}>
                  <Text>{index + 1}、{item.name}</Text>
                  <AtIcon value='close' size='18'
                    onClick={() => {
                      let list = this.props.newList
                      for (var i = 0; i < list.length; i++) {
                        if (list[i].id == item.id) {
                          list.splice(i, 1)
                          this.setState({
                            newList: list
                          })
                        }
                      }
                    }}
                  />
                </View>
              )
            }
            <View className="cltips">增加企业：搜索增加更多企业</View>
            <View className="cltips">删除企业：点击“X”删除公出列表</View>
          </View>
        }

        {
          this.props.jsList.length > 0 && this.props.type == 1 &&
          <View className="slist">
            <View style={{ fontSize: "30rpx" }}>本次公出列表</View>
            {
              this.props.jsList.map((item, index) =>
                <View className="slitems" key={index}>
                  <Text>{index + 1}、{item.name}{!!item.contractNo && `(${item.contractNo})`}</Text>
                  <AtIcon value='close' size='18'
                    onClick={() => {
                      let list = this.props.jsList
                      for (var i = 0; i < list.length; i++) {
                        if (list[i].id == item.id) {
                          list.splice(i, 1)
                          this.setState({
                            jsList: list
                          })
                        }
                      }
                    }}
                  />
                </View>
              )
            }
            <View className="cltips">增加企业：搜索增加更多企业</View>
            <View className="cltips">删除企业：点击“X”删除公出列表</View>
          </View>
        }

        <View>
          {this.props.type == 0 || this.props.type == 2 ? (
            <View>
              {" "}
              {this.state.list.map((v, k) => (
                <View
                  style={{
                    padding: "10px",
                    display: "flex",
                    flexFlow: "row",
                    alignItems: "center",
                    justifyContent: "space-between",
                    borderBottom: "1px #ece6e6 solid",
                  }}
                  key={k}
                  onClick={() => {

                    this.checkUserArchives(v)

                  }}
                >
                  <View style={{ fontSize: "15px" }}>{v.name}</View>
                  {this.state.selectId === v.id ? (
                    <Icon size="20" type="success_no_circle" />
                  ) : null}
                </View>
              ))}{" "}
              <ListBottomStart
                type="pagination"
                pageSize={10}
                state={this.state.listState}
                total={this.state.totalCount}
                current={this.state.pageNo}
                onPageChange={(type, current) => {
                  this.getList(this.state.value, current);
                }}
                reload={() => {
                  this.getList(this.state.value);
                }}
              />{" "}
            </View>
          ) : !this.state.listVisible ? (
            <View>
              {this.state.list.map((v, k) => (
                <View
                  style={{
                    padding: "10px",
                    display: "flex",
                    flexFlow: "row",
                    alignItems: "center",
                    justifyContent: "space-between",
                    borderBottom: "1px #ece6e6 solid",
                  }}
                  key={k}
                  onClick={() => {
                    let select = 0
                    if (this.props.jsList.length == 0) {
                      select = 0
                    }
                    for (var i = 0; i < this.props.jsList.length; i++) {
                      if (!!this.props.jsList[i].contractNo) {
                        select = 1
                      }
                    }
                    if (select == 0) {
                      this.setState({
                        listVisible: true,
                        listValue: v,
                      });
                      this.getByUid(v);
                    } else {
                      let list = this.props.jsList
                      for (var i = 0; i < list.length; i++) {
                        if (list[i].id == v.id) {
                          Taro.showToast({
                            title: "该企业已在公出列表中",
                            icon: 'none'
                          })
                          return
                        }
                      }
                      list.push(v)
                      this.setState({
                        jsList: list
                      })
                    }

                    // this.setState({
                    //   // selectId:v.id
                    //   listValue: v,
                    //   listVisible: true,
                    // });
                    // this.getByUid(v);
                    // this.props.onVisible()
                    // this.props.onChange({uid:v.id,nickname:v.name});
                  }}
                >
                  <View style={{ fontSize: "15px" }}>{v.name}</View>
                  {this.state.selectId === v.id ? (
                    <Icon size="20" type="success_no_circle" />
                  ) : null}
                </View>
              ))}{" "}
              <ListBottomStart
                type="pagination"
                pageSize={10}
                state={this.state.listState}
                total={this.state.totalCount}
                current={this.state.pageNo}
                onPageChange={(type, current) => {
                  this.getList(this.state.value, current);
                }}
                reload={() => {
                  this.getList(this.state.value);
                }}
              />{" "}
            </View>
          ) : (
            ""
          )}
          {this.state.listVisible && this.props.type == 1 ? (
            <View>
              <AtListItem
                title={this.state.listValue.name}
                arrow="right"
                iconInfo={{ size: 25, color: "#000000", value: "bookmark" }}
              />
              <View>
                {this.state.orderNo.length > 0 ? (
                  <View>
                    {" "}
                    {this.state.orderNo.map((v, k) => (
                      <View
                        key={k}
                        style={{
                          display: "flex",
                          justifyContent: " center",
                          marginBottom: "20px",
                        }}
                      >
                        编号:<View>{v.contractNo}</View>
                        <View
                          style={{
                            width: "60px",
                            height: "24px",
                            backgroundColor: "#5599FF",
                            borderRadius: "15px",
                            textAlign: "center",
                            lineHeight: "24px",
                            marginLeft: "20px",
                            color: "white",
                          }}
                          circle
                          onClick={() => {
                            this.setState({
                              listVisible: false,
                            });
                            v.id = this.state.listValue.id;
                            v.name = this.state.listValue.name;

                            let list = this.props.jsList
                            list.push(v)
                            this.setState({
                              jsList: list
                            })

                            // this.props.onChange(
                            //   {
                            //     uids: v.id,
                            //     userNames: v.name,
                            //     orderNo: v.orderNo,
                            //     contractNo: v.contractNo,
                            //   },
                            //   1
                            // );
                            // Taro.eventCenter.trigger('enterprise', v)
                          }}
                        >
                          选择
                        </View>
                      </View>
                    ))}
                    <View
                      style={{ color: "red", width: "260px", margin: "0 auto" }}
                    >
                      注:请选择正确的派单编号！公出信息将统计至对应的订单中。
                    </View>
                  </View>
                ) : (
                  <View style={{ color: "red" }}>
                    该企业暂无订单,无法技术公出!请联系营销员查询派单情况
                  </View>
                )}
              </View>
            </View>
          ) : (
            ""
          )}
        </View>
      </>
    );
  }
}

export default Enterprise;
