import React, { Component } from "react";
import { View, Button, Text, Picker } from "@tarojs/components";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import {
  AtButton,
  AtSearchBar,
  AtCheckbox,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtInput,
  AtTextarea,
  AtIcon,
} from "taro-ui";
import {
  checkUserName,
  getBusinessProjectByName,
  addCustomer,
  addChannel,
} from "../../utils/servers/servers";
import { getProvince } from '../../utils/tools/index'
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/button.scss";
import "taro-ui/dist/style/components/search-bar.scss";
import "taro-ui/dist/style/components/checkbox.scss";

import MessageNoticebar from "../../components/common/messageNoticebar";
import AddressPicker from "../../components/common/addressPicker";
import CustomNatureSelect from "../../components/common/CustomNatureSelect";

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

  constructor(props) {
    super(props);
    this.state = {
      isOpened: false,
      info: {
        name: "",
      },
      pickerShow: false,
      isProject: false,
      options: [],
      checkOptions: [],
      channelTypeList: [
        { id: 2, title: "民主党派" },
        { id: 3, title: "园区" },
        { id: 4, title: "民间组织" },
        { id: 5, title: "战略合作单位" },
        { id: 1, title: "其他" },
      ],
      channe: "",
      selChannelType: 0,
      levelList: [
        { id: 0, title: "一般客户（一年以上预签）" },
        { id: 1, title: "意向客户（半年内预签）" },
        { id: 2, title: "重点客户（一个月内预签）" },
      ],
      naturePickerShow: false,
      // natureOptions1: [{
      //   id: 1,
      //   title: "政府机构"
      // }, {
      //   id: 2,
      //   title: "科研院所"
      // }, {
      //   id: 3,
      //   title: "高等院校"
      // }, {
      //   id: 4,
      //   title: "社会团体"
      // }, {
      //   id: 5,
      //   title: "企业"
      // }, {
      //   id: 0,
      //   title: "其他组织"
      // }],
      // natureOptions2: [{
      //   id: 1,
      //   title: "国企"
      // }, {
      //   id: 2,
      //   title: "央企"
      // }, {
      //   id: 3,
      //   title: "私企"
      // }, {
      //   id: 4,
      //   title: "合资企业（含港澳台）"
      // }, {
      //   id: 5,
      //   title: "外资控股"
      // }],
      // natureOptions3: [{
      //   id: 1,
      //   title: "上市公司",
      // }, {
      //   id: 0,
      //   title: "非上市公司",
      // }],
      // natureList: []
    };
    this.checkUserName = this.checkUserName.bind(this);
    this.onSearchChange = this.onSearchChange.bind(this);
    this.submit = this.submit.bind(this);
    this.channeSubmit = this.channeSubmit.bind(this);
  }

  componentDidMount() {
  }

  componentDidShow() {

  }
  // 公司名称验证
  checkUserName() {
    const { info } = this.state
    let yzName = info.name
    if (!yzName) {
      Taro.showToast({ title: "请输入公司名称", icon: "none" });
      return
    }
    let re = new RegExp("^[\u4e00-\u9fa5]");
    if (!re.test(yzName)) {
      Taro.showToast({ title: "公司名称必须以汉字开头！", icon: "none" });
      return
    }
    if (!re.test(yzName.charAt(yzName.length - 1))) {
      Taro.showToast({ title: "公司名称必须以汉字结尾！", icon: "none" });
      return
    }
    if (yzName.length > 64) {
      Taro.showToast({ title: "公司名称字数不超过64个！", icon: "none" });
      return
    };
    let regu = /[`~!#$%^&*'_[\]+=<>?:"{}|~！#￥%……&*=-@-!{}|/《》？：“”【】、；;‘’，,.。、\s+]/g;
    if (regu.test(yzName)) {
      Taro.showToast({ title: "公司名称不能存在特殊符号或空格！", icon: "none" });
      return
    }
    checkUserName({
      userName: yzName
    })
      .then((v) => {
        if (v.error.length === 0) {
          if (v.data) {
            this.setState({
              isOpened: true
            })
          } else {
            Taro.showToast({ title: "", icon: "success" });
            this.setState({
              isOpened: false
            })
          }
        }
      })
      .catch((err) => {
        Taro.showToast({ title: "系统错误,请稍后再试", icon: "none" });
      })
  }

  // 项目列表
  getBusinessProjectByName(val) {
    getBusinessProjectByName({
      businessName: val || "",
    })
      .then((v) => {
        if (v.error.length === 0) {
          let theArr = [];
          if (v.data.length > 0) {
            for (let i = 0; i < v.data.length; i++) {
              let thisdata = v.data[i];
              theArr.push({
                value: thisdata.bname,
                label: thisdata.bname,
              });
            };
          }
          this.setState({
            options: theArr
          })
        } else {
          Taro.showToast({ title: v.error[0].message, icon: "none" });
        }
      })
      .catch((err) => {
        Taro.showToast({ title: "系统错误,请稍后再试", icon: "none" });
      });
  }

  onSearchChange(value) {
    this.setState({
      value,
    });
  }

  // 新增企业
  submit() {
    const { info } = this.state
    let re = new RegExp("^[\u4e00-\u9fa5]");
    if (!re.test(info.name)) {
      Taro.showToast({ title: "公司名称必须以汉字开头！", icon: "none" });
      return
    }
    if (!re.test(info.name.charAt(info.name.length - 1))) {
      Taro.showToast({ title: "公司名称必须以汉字结尾！", icon: "none" });
      return
    }
    if (info.name.length > 64) {
      Taro.showToast({ title: "公司名称字数不超过64个！", icon: "none" });
      return
    };
    let regu = /[`~!#$%^&*'_[\]+=<>?:"{}|~！#￥%……&*=-@-!{}|/《》？：“”【】、；;‘’，,.。、\s+]/g;
    if (regu.test(info.name)) {
      Taro.showToast({ title: "公司名称不能存在特殊符号或空格!", icon: "none" });
      return
    }
    if (!/^[A-Z0-9]{15}$|^[A-Z0-9]{17}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$/.test(info.orgCode)) {
      Taro.showToast({ title: "请输入正确的统一社会信用代码！", icon: "none" });
      return
    }
    if (!info.province) {
      Taro.showToast({ title: "请选择地区", icon: "none" });
      return
    };
    if (/.*[\u4e00-\u9fa5]+.*$/.test(info.contacts)) {
    } else {
      Taro.showToast({ title: "请填写正确的联系人，且至少包含一个汉字", icon: "none" });
      return
    };
    if (info.contacts.length > 32) {
      Taro.showToast({ title: "联系人字数不超过32个", icon: "none" });
      return
    };
    if (/.*[\u4e00-\u9fa5]+.*$/.test(info.position)) {
    } else {
      Taro.showToast({ title: "请填写正确的职位，且至少包含一个汉字", icon: "none" });
      return
    };
    let regeX1 = /^1[3456789]\d{9}$/;
    let regex2 = /^((0\d{2,3})-)?(\d{7,8})$/;
    if (regeX1.test(info.contactMobile) == false && regex2.test(info.contactMobile) == false) {
      Taro.showToast({ title: "请填写正确的联系电话", icon: "none" });
      return
    }
    if (!info.businessScope) {
      Taro.showToast({ title: "请选择主营产品", icon: "none" });
      return
    }
    if (!info.intendedProject) {
      Taro.showToast({ title: "请选择意向合作项目", icon: "none" });
      return
    }
    console.log(info.level)
    if (info.level === undefined || info.level === null) {
      Taro.showToast({ title: "请选择客户类型", icon: "none" });
      return
    }
    if (!info.nature) {
      Taro.showToast({ title: "请选择客户性质", icon: "none" });
      return
    }
    if (info.nature && info.nature[0] == 0 && !info.natureOther) {
      Taro.showToast({ title: "请输入其他说明", icon: "none" });
      return
    }
    info.societyTag = '0'
    info.type = '1'
    let addList = getProvince(info.province, info.city, info.area)

    let enterpriseNature = undefined; // 企业性质 0=其他，1=国企，2=央企，3=私企，4=合资企业（含港澳台），5=外资控股
    let listedNature = undefined; // 上市 0=否，1=是
    if (info.nature.length >= 2) {
      enterpriseNature = info.nature[1];
    }
    if (info.nature.length >= 3) {
      listedNature = info.nature[2];
    }

    let params = { ...this.state.info };
    params.nature = params.nature[0];
    if(enterpriseNature) {
      params.enterpriseNature = enterpriseNature;
    }
    if (listedNature) {
      params.listedNature = listedNature;
    }
    delete params.natureName;

    Taro.showLoading({
      title: '保存中...',
    })
    addCustomer({
      ...params,
      ...{
        province: addList[0],
        city: addList[1],
        area: addList[2],
      }
    })
      .then((v) => {
        Taro.hideLoading()
        if (v.error.length === 0) {
          Taro.showToast({ title: "保存成功", icon: "success" });
          setTimeout(() => {
            Taro.switchTab({
              url: '/pages/enterprise/index'
            })
          }, 800);
        } else {
          Taro.showToast({ title: v.error[0].message, icon: "none" });
        }
      })
      .catch((err) => {
        Taro.hideLoading()
        Taro.showToast({ title: "系统错误,请稍后再试", icon: "none" });
        // console.log(err);
      });
  }

  // 新增渠道
  channeSubmit() {
    const { info } = this.state
    if (!info.name) {
      Taro.showToast({ title: "请填写渠道名称", icon: "none" });
      return
    }
    if (info.name.length > 64) {
      Taro.showToast({ title: "渠道名称字数不超过64个", icon: "none" });
      return
    }
    let regu = /[`~!#$%^&*'_[\]+=<>?:"{}|~！#￥%……&*=-@-!{}|/《》？：“”【】、；;‘’，,.。、\s+]/g;
    if (regu.test(info.name)) {
      Taro.showToast({ title: "渠道名称不能存在特殊符号!", icon: "none" });
      return
    }
    if (!info.channelType) {
      Taro.showToast({ title: "请选择渠道类别", icon: "none" });
      return
    }
    if (!info.province) {
      Taro.showToast({ title: "请选择地区", icon: "none" });
      return
    };
    if (/.*[\u4e00-\u9fa5]+.*$/.test(info.contacts)) {
    } else {
      Taro.showToast({ title: "请填写正确的联系人，且至少包含一个汉字", icon: "none" });
      return
    }
    if (info.contacts.length > 32) {
      Taro.showToast({ title: "联系人字数不超过32个", icon: "none" });
      return
    }
    if (/.*[\u4e00-\u9fa5]+.*$/.test(info.position)) {
    } else {
      Taro.showToast({ title: "请填写正确的职位，且至少包含一个汉字", icon: "none" });
      return
    }
    let regeX1 = /^1[3456789]\d{9}$/;
    let regex2 = /^((0\d{2,3})-)?(\d{7,8})$/;
    if (regeX1.test(info.contactMobile) == false && regex2.test(info.contactMobile) == false) {
      Taro.showToast({ title: "请填写正确的联系电话", icon: "none" });
      return
    }
    if (info.introduction.length === 0) {
      Taro.showToast({ title: "请填写渠道简介", icon: "none" });
      return
    }
    let addList = getProvince(info.province, info.city, info.area)
    Taro.showLoading({
      title: '保存中...',
    })
    addChannel({
      ...info,
      ...{
        province: addList[0],
        city: addList[1],
        area: addList[2],
      }
    })
      .then((v) => {
        if (v.error.length === 0) {
          Taro.hideLoading()
          Taro.showToast({ title: "保存成功", icon: "success" });
          setTimeout(() => {
            Taro.switchTab({
              url: '/pages/enterprise/index'
            })
          }, 800);
        } else {
          Taro.showToast({ title: v.error[0].message, icon: "none" });
        }
      })
      .catch((err) => {
        Taro.hideLoading()
        Taro.showToast({ title: "系统错误,请稍后再试", icon: "none" });
      });
  }

  toggleAddressPicker(e, params) {
    const { info } = this.state
    if (params) {
      this.setState({
        pickerShow: false,
        info: Object.assign(info, {
          province: e.province,
          city: e.city,
          area: e.area,
        })
      })
    } else {
      this.setState({
        pickerShow: false
      })
    }
  }

  handleNatureToggleShow(e, params) {
    if (params) {
      const { info } = this.state;
      info.nature = e.id;
      info.natureName = e.name.join('\/');
      console.log(info)
      this.setState({ info, naturePickerShow: false });
    } else {
      this.setState({ naturePickerShow: false });
    }
  }

  render() {
    const { info, isOpened, pickerShow, isProject, checkOptions, channelTypeList, channe } = this.state;
    return (
      <View className="addEnterprise">
        <MessageNoticebar />
        {
          this.$instance.router.params.type == "1" &&
          <View className="form">
            <AtInput
              succes
              required
              name='name'
              title='公司名称'
              type='text'
              placeholder='请填写公司名称'
              value={info.name}
              onChange={e => {
                this.setState({
                  info: Object.assign(info, {
                    name: e
                  })
                })
              }}
              cursor={-1}
            >
              <View onClick={this.checkUserName}>验证</View>
            </AtInput>
            <AtInput
              required
              name='orgCode'
              title='统一社会信用代码'
              type='text'
              placeholder='请填写统一社会信用代码'
              value={info.orgCode}
              onChange={e => {
                this.setState({
                  info: Object.assign(info, {
                    orgCode: e
                  })
                })
              }}
              cursor={-1}
            />
            <View className="aitem">
              <View className="atit">
                <Text className="atip">*</Text>
                省-市-区
              </View>
              <View className={!!info.province ? "avals" : "aval"} onClick={() => { this.setState({ pickerShow: true }) }}>
                {!!info.province ? (info.province || "") + (!info.city ? "" : "-") + (info.city || "") + (!info.area ? "" : "-") + (info.area || "") : "点击选择"}
              </View>
              { pickerShow && <AddressPicker
                pickerShow={pickerShow}
                onHandleToggleShow={this.toggleAddressPicker.bind(this)}
              />}
            </View>
            <AtInput
              required
              name='contacts'
              title='联系人'
              type='text'
              placeholder='请填写联系人名称'
              value={info.contacts}
              onChange={e => {
                this.setState({
                  info: Object.assign(info, {
                    contacts: e
                  })
                })
              }}
              cursor={-1}
            />
            <AtInput
              required
              name='position'
              title='职位'
              type='text'
              placeholder='请填写联系人职位'
              value={info.position}
              onChange={e => {
                this.setState({
                  info: Object.assign(info, {
                    position: e
                  })
                })
              }}
              cursor={-1}
            />
            <AtInput
              required
              name='contactMobile'
              title='联系电话'
              type='number'
              placeholder='请填写联系人电话'
              value={info.contactMobile}
              onChange={e => {
                this.setState({
                  info: Object.assign(info, {
                    contactMobile: e
                  })
                })
              }}
              cursor={-1}
            />
            <AtInput
              required
              name='businessScope'
              title='主营产品/服务'
              type='text'
              placeholder='请用,符号隔开关键词'
              value={info.businessScope}
              onChange={e => {
                this.setState({
                  info: Object.assign(info, {
                    businessScope: e
                  })
                })
              }}
              cursor={-1}
            />
            <View className="aitem">
              <View className="atit">
                <Text className="atip">*</Text>
                意向合作项目
              </View>
              <View className={!!info.intendedProject ? "avals" : "aval"}
                onClick={() => {
                  this.getBusinessProjectByName("")
                  this.setState({
                    isProject: true
                  })
                }}>{!!info.intendedProject ? info.intendedProject : "点击选择"}</View>
            </View>

            <View className="aitem">
              <View className="atit">
                <Text className="atip">*</Text>
                客户类型
              </View>
              <Picker
                value={this.state.level}
                range={this.state.levelList} rangeKey='title' mode='selector'
                onChange={(e) => {
                  this.setState({
                    levelName: this.state.levelList[e.detail.value].title,
                    level: e.detail.value,
                    info: Object.assign(info, {
                      level: Number(e.target.value),
                    })
                  })
                }}>
                <View className={!!this.state.level ? "avals" : "aval"} style={{ width: "233px" }}>
                  {!!this.state.levelName ? this.state.levelName : "请选择"}
                </View>
              </Picker>
            </View>

            <View className="aitem">
              <View className="atit">
                <Text className="atip">*</Text>
                客户性质
              </View>

              <View className={!!info.natureName ? "avals" : "aval"} onClick={() => {
                this.setState({ naturePickerShow: true }, () => {
                  console.log(this.state.naturePickerShow)
                })
              }}>
                {!!info.natureName ? info.natureName : "点击选择"}
              </View>

              { this.state.naturePickerShow ? (
                <CustomNatureSelect
                  pickerShow={this.state.naturePickerShow}
                  onHandleToggleShow={this.handleNatureToggleShow.bind(this)}
                />
              ) : null }
            </View>

            { info.nature && info.nature[0] == 0 ? (
              <View className="aitem" style={{ alignItems: "flex-start" }}>
                <View className="atit">
                  <Text className="atip">*</Text>
                  其他说明
                </View>
                <View className="avals">
                  <AtTextarea
                    value={info.natureOther}
                    onChange={e => {
                      this.setState({
                        info: Object.assign(info, {
                          natureOther: e
                        })
                      })
                    }}
                    maxLength={200}
                    placeholder='请输入其他说明'
                  />
                </View>
              </View>
            ) : null}
            
            <View className="bottom">
              <AtButton type='primary' onClick={this.submit}>保存</AtButton>
              {/* <AtButton type='secondary' size='small'>取消</AtButton> */}
            </View>
          </View>
        }
        {
          this.$instance.router.params.type == "2" &&
          <View className="form">
            <AtInput
              succes
              required
              name='name'
              title='渠道名称'
              type='text'
              placeholder='请填写渠道名称'
              value={info.name}
              onChange={e => {
                this.setState({
                  info: Object.assign(info, {
                    name: e
                  })
                })
              }}
              cursor={-1}
            >
              <View onClick={this.checkUserName}>验证</View>
            </AtInput>


            <View className="aitem">
              <View className="atit">
                <Text className="atip">*</Text>
                渠道类别
              </View>
              <Picker
                value={this.state.selChannelType}
                range={channelTypeList} rangeKey='title' mode='selector'
                onChange={(e) => {
                  this.setState({
                    channe: channelTypeList[e.detail.value].title,
                    selChannelType: e.detail.value,
                    info: Object.assign(info, {
                      channelType: channelTypeList[e.detail.value].id,
                    })
                  })
                }}>
                <View className={!!channe ? "avals" : "aval"} style={{ width: "233px" }}>
                  {!!channe ? channe : "请选择"}
                </View>
              </Picker>
            </View>
            {
              !!info.channelType &&
              <View>
                <View className="aitem">
                  <View className="atit">
                    <Text className="atip">*</Text>
                    省-市-区
                  </View>
                  <View className={!!info.province ? "avals" : "aval"} onClick={() => { this.setState({ pickerShow: true }) }}>
                    {!!info.province ? (info.province || "") + (!info.city ? "" : "-") + (info.city || "") + (!info.area ? "" : "-") + (info.area || "") : "点击选择"}
                  </View>
                  { pickerShow &&  <AddressPicker
                    pickerShow={pickerShow}
                    onHandleToggleShow={this.toggleAddressPicker.bind(this)}
                  />}
                </View>
                <AtInput
                  required
                  name='contacts'
                  title='联系人'
                  type='text'
                  placeholder='请填写联系人名称'
                  value={info.contacts}
                  onChange={e => {
                    this.setState({
                      info: Object.assign(info, {
                        contacts: e
                      })
                    })
                  }}
                  cursor={-1}
                />
                <AtInput
                  required
                  name='position'
                  title='职位'
                  type='text'
                  placeholder='请填写联系人职位'
                  value={info.position}
                  onChange={e => {
                    this.setState({
                      info: Object.assign(info, {
                        position: e
                      })
                    })
                  }}
                  cursor={-1}
                />
                <AtInput
                  required
                  name='contactMobile'
                  title='联系电话'
                  type='number'
                  placeholder='请填写联系人电话'
                  value={info.contactMobile}
                  onChange={e => {
                    this.setState({
                      info: Object.assign(info, {
                        contactMobile: e
                      })
                    })
                  }}
                  cursor={-1}
                />
                <View className="aitem" style={{ alignItems: "flex-start" }}>
                  <View className="atit">
                    <Text className="atip">*</Text>
                    渠道简介
                  </View>
                  <View className="avals">
                    <AtTextarea
                      value={info.introduction}
                      onChange={e => {
                        this.setState({
                          info: Object.assign(info, {
                            introduction: e
                          })
                        })
                      }}
                      maxLength={200}
                      placeholder='请填写渠道简介'
                    />
                  </View>
                </View>
              </View>
            }
            <View className="bottom">
              <AtButton type='primary' onClick={this.channeSubmit}>保存</AtButton>
              {/* <AtButton type='secondary' size='small'>取消</AtButton> */}
            </View>
          </View>
        }
        <AtModal
          isOpened={isOpened}
          title='提醒'
          confirmText='确认'
          onClose={() => { this.setState({ isOpened: false, }) }}
          onConfirm={() => { this.setState({ isOpened: false }) }}
          content='企业客户已存在！请在“客户管理-企业客户-企业客户查询”输入企业全称查询所属人信息'
        />
        <AtModal
          isOpened={isProject}
          closeOnClickOverlay={false}
        >
          <AtModalHeader>请选择项目</AtModalHeader>
          <AtModalContent>
            <AtSearchBar
              placeholder="请输入项目名称"
              showActionButton
              value={this.state.value}
              onChange={this.onSearchChange}
              onActionClick={() => {
                this.getBusinessProjectByName(this.state.value);
              }}
              onClear={() => {
                this.setState({
                  value: "",
                }, () => { this.getBusinessProjectByName(this.state.value) });
              }}
            />
            {
              checkOptions.length > 0 &&
              <View className="selproject">
                已选择：
                {
                  checkOptions.map((v, i) =>
                    <View className="selptxt" key={i}
                      onClick={() => {
                        let list = checkOptions
                        for (var j = 0; j < list.length; j++) {
                          if (list[j] == v) {
                            list.splice(j, 1)
                            this.setState({
                              checkOptions: list,
                              info: Object.assign(info, {
                                intendedProject: list.toString(),
                              }),
                            })
                          }
                        }
                      }}
                    >{v}&nbsp;<AtIcon className='atIcon' value='close-circle' size='12' color='#fff' /></View>
                  )
                }
              </View>
            }
            <AtCheckbox
              options={this.state.options}
              selectedList={checkOptions}
              onChange={e => {
                this.setState({
                  checkOptions: e,
                })
              }}
            />
          </AtModalContent>
          <AtModalAction>
            {/* <Button type='secondary' onClick={() => { this.setState({ isProject: false, }) }}>取消</Button> */}
            <Button type='primary'
              onClick={() => {
                this.setState({
                  isProject: false,
                  info: Object.assign(info, {
                    intendedProject: checkOptions.toString(),
                  }),
                })
              }}>确定</Button>
          </AtModalAction>
        </AtModal>

      </View >
    );
  }
}

export default AddEnterprise;
