import React, { Component } from "react";
import { View, Text, Icon } from "@tarojs/components";
import {
  getUserByName,
  getOrderByUid,
  getRestrictProjectUser,
  checkUserArchives,
} from "../../utils/servers/servers";
import { AtSearchBar, AtListItem, AtButton, AtIcon } 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/icon.scss";
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/icon.scss";
import ListBottomStart from "../../components/common/listBottomStart";
import "./enterprise.less";
import Taro from "@tarojs/taro";

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

  componentDidMount() {
    Taro.eventCenter.on("result", () => {
      this.setState({
        value: "",
        list: [],
        newList: [],
        listState: "NO_DATA",
        pageNo: 1,
      });
    });
    Taro.eventCenter.on("applyDepartSearchList", () => {
      this.getList(this.state.value, this.state.pageNo + 1);
    });
  }

  componentDidUpdate(props) {
    if (props.type !== this.props.type) {
      this.setState({
        newList: []
      })
    }
  }

  getRestrictProjectUser() {
    getRestrictProjectUser({
      ids: this.state.newList.map(obj => { return obj.id; }).join(","),
    })
      .then((v) => {
        if (v.error.length === 0) {
          Taro.eventCenter.trigger("enterprise",
            {
              id: this.state.newList.map(obj => { return obj.id; }).join(","),
              name: this.state.newList.map(obj => { return obj.name; }).join(","),
              list: this.state.newList,
              userList: v.data,
            }
          );
        } else {
          Taro.showToast({
            title: v.error[0].message,
            icon: "none",
          });
        }
      })
      .catch((err) => {

      });
  }

  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);
  }

  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) {
    this.setState({
      listState: "LOADING",
    });
    getUserByName({
      name: value,
      type: 1,
      pageNo: pageNo,
      pageSize: 10,
    })
      .then((msg) => {
        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:
              pageNo === 1
                ? msg.data.list
                : this.state.list.concat(msg.data.list),
            pageNo: msg.data.pageNo,
          });
        } else {
          Taro.showToast({ title: msg.error[0].message, icon: "none" });
          this.setState({
            listState: msg.error[0].field === "403" ? "NO_DATA" : "RELOAD",
          });
        }
      })
      .catch(() => {
        this.setState({
          listState: "RELOAD",
        });
      });
  }

  checkUserArchives(v) {

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

    let list = this.state.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
          placeholder="请输入企业/渠道"
          showActionButton
          value={this.state.value}
          onChange={this.onChange}
          onActionClick={() => {
            this.setState({
              listVisible: false,
            });
            this.onChange(this.state.value, false);
          }}
          onConfirm={() => {
            this.onChange(this.state.value, false);
          }}
          onClear={() => {
            this.setState({
              value: "",
              list: [],
              listState: "NO_DATA",
              pageNo: 1,
              listVisible: false,
            });
          }}
        />
        {/* 业务行政公出 */}
        {
          this.state.newList.length > 0 && this.props.type != 1 &&
          <View className="slist">
            <View style={{ fontSize: "30rpx" }}>本次公出列表</View>
            {
              this.state.newList.map((item, index) =>
                <View className="slitems" key={index}>
                  <Text>{index + 1}、{item.name}</Text>
                  <AtIcon value='close' size='18'
                    onClick={() => {
                      let list = this.state.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="slbt">
              <AtButton size="small" type='primary'
                onClick={() => {
                  this.getRestrictProjectUser()
                }}
              >确定公出列表</AtButton>
            </View>
            <View className="cltips">增加企业:搜索增加更多企业，删除企业:点击“X”删除公出列表</View>
          </View>
        }
        {/* 技术公出 */}
        {
          this.state.jsList.length > 0 && this.props.type == 1 &&
          <View className="slist">
            <View style={{ fontSize: "30rpx" }}>本次公出列表</View>
            {
              this.state.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.state.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="slbt">
              <AtButton size="small" type='primary'
                onClick={() => {
                  let contractNo = ""
                  let orderNo = ""
                  let select = 0
                  for (var i = 0; i < this.state.jsList.length; i++) {
                    if (!!this.state.jsList[i].contractNo) {
                      contractNo = this.state.jsList[i].contractNo
                      orderNo = this.state.jsList[i].orderNo
                      select = 1
                    }
                  }
                  if (select == 0) {
                    Taro.showToast({
                      title: "必须选择一个派单编号",
                      icon: 'none'
                    })
                    return
                  }
                  Taro.eventCenter.trigger("enterprise",
                    {
                      id: this.state.jsList.map(obj => { return obj.id; }).join(","),
                      name: this.state.jsList.map(obj => { return obj.name; }).join(","),
                      list: this.state.jsList,
                      contractNo,
                      orderNo,
                    }
                  );
                }}
              >确定公出列表</AtButton>
            </View>
            <View className="cltips">增加企业:搜索增加更多企业，删除企业:点击“X”删除公出列表</View>
          </View>
        }

        <View>
          {this.props.type == 0 || this.props.type == 2
            ? this.state.list.map((v, k) => (
              <View key={k}>
                <AtListItem
                  title={v.name}
                  arrow="right"
                  iconInfo={{ size: 25, color: "#000000", value: "bookmark" }}
                  onClick={() => {

                    this.checkUserArchives(v)

                    // Taro.eventCenter.trigger("enterprise", v);
                  }}
                />
              </View>
            ))
            : !this.state.listVisible
              ? this.state.list.map((v, k) => (
                <View key={k}>
                  <AtListItem
                    title={v.name}
                    arrow="right"
                    iconInfo={{ size: 25, color: "#000000", value: "bookmark" }}
                    onClick={() => {
                      let select = 0
                      if (this.state.jsList.length == 0) {
                        select = 0
                      }
                      for (var i = 0; i < this.state.jsList.length; i++) {
                        if (!!this.state.jsList[i].contractNo) {
                          select = 1
                        }
                      }
                      if (select == 0) {
                        this.setState({
                          listVisible: true,
                          listValue: v,
                        });
                        this.getByUid(v);
                      } else {
                        let list = this.state.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
                        })
                      }

                    }}
                  />
                </View>
              ))
              : ""}
          {this.state.listVisible && this.props.type == 1 ? (
            <View>
              <AtListItem
                title={this.state.listValue.name}
                arrow="right"
                iconInfo={{ size: 25, color: "#000000", value: "bookmark" }}
              />
              {
                this.state.listState == "NO_MORE_DATA" &&
                <View style={{ marginTop: "10px" }}>
                  {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.name = this.state.listValue.name;
                              v.id = this.state.listValue.id;
                              v.aname = this.state.listValue.aname;
                              v.aid = this.state.listValue.aid;
                              v.status = this.state.listValue.status;
                              let list = this.state.jsList
                              list.push(v)
                              this.setState({
                                jsList: list
                              })
                              // Taro.eventCenter.trigger("enterprise", v);
                            }}
                          >
                            选择
                          </View>
                        </View>
                      ))}{" "}
                      <View style={{ color: "red", width: "260px", margin: "0 auto" }}>
                        注:请选择正确的派单编号！公出信息将统计至对应的订单中。
                      </View>
                    </View>
                  ) :
                    <View style={{ color: "red", width: "260px", margin: "0 auto" }}>
                      该企业暂无订单,无法技术公出!请联系营销员查询派单情况
                    </View>}
                </View>
              }
            </View>
          ) : (
            ""
          )}
          <ListBottomStart
            state={this.state.listState}
            reload={() => {
              this.onChange(this.state.value);
            }}
          />
        </View>
      </>
    );
  }
}

export default Enterprise;
