import React from "react";
import {
  Table,
  Button,
  Spin,
  message,
  Popconfirm,
  Alert,
  Modal,
  Input,
  Cascader,
} from "antd";
const TextArea = Input.TextArea;
import $ from "jquery/src/ajax";
import AddContact from "../../../customer/NEW/signCustomer/followDetail/addContact";
import "./index.less";
import { areaSelect, getProvince } from "@/NewDicProvinceList";

const ContactPerson = React.createClass({
  getInitialState() {
    return {
      major: 0,
      loading: false,
      addcontactModul: false,
      enterpriseName: "",
      ContactsLists: [
        {
          title: "姓名",
          dataIndex: "name",
          key: "name",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "联系人部门",
          dataIndex: "department",
          key: "department",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "联系人职务",
          dataIndex: "position",
          key: "position",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "主要联系人",
          dataIndex: "major",
          width: 100,
          key: "major",
          render: (text) => {
            return text == 1 ? "是" : "否";
          },
        },
        {
          title: "地区",
          dataIndex: "cityName",
          key: "cityName",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "手机号码",
          dataIndex: "mobile",
          key: "mobile",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "座机",
          dataIndex: "fixedTel",
          key: "fixedTel",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "微信",
          dataIndex: "wechat",
          key: "wechat",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "联系人QQ",
          dataIndex: "qq",
          key: "qq",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "电子邮箱",
          dataIndex: "email",
          key: "email",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "更新时间",
          dataIndex: "createTimes",
          key: "createTimes",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "跟进人",
          dataIndex: "aname",
          key: "aname",
          render: (text, record, index) => {
            if (record.id) return <div>{text}</div>;
          },
        },
        {
          title: "操作",
          dataIndex: "dels",
          key: "dels",
          render: (text, record, index) => {
            return (
              !this.props.isCustomerAdmin && (
                <div>
                  {adminData.isSuperAdmin || !record.id ? (
                    <Popconfirm
                      title="是否删除?"
                      onConfirm={(e) => {
                        this.confirmDelet(record);
                      }}
                      okText="删除"
                      cancelText="不删除"
                    >
                      <Button
                        style={{
                          marginRight: "10px",
                          color: "#ffffff",
                          background: "#f00",
                          border: "none",
                        }}
                      >
                        删除
                      </Button>
                    </Popconfirm>
                  ) : (
                    ""
                  )}
                  {record.major != 1 ? (
                    <Button
                      style={{
                        marginRight: "10px",
                        color: "#ffffff",
                        background: "green",
                        border: "none",
                      }}
                      onClick={(e) => {
                        e.stopPropagation(), this.mainContact(record);
                      }}
                    >
                      设为主要联系人
                    </Button>
                  ) : (
                    ""
                  )}
                </div>
              )
            );
          },
        },
      ],
      visible: "", //修改弹窗状态
      name: "",
      locationProvince: "",
      introduction: "",
      newname: "",
      dataArrar: [],
      newintroduction: "",
    };
  },
  //tab2删除
  confirmDelet(e) {
    this.setState({
      loading: true,
    });
    if (e.id) {
      $.ajax({
        method: "get",
        dataType: "json",
        crossDomain: false,
        url: globalConfig.context + "/api/admin/customer/deleteOneContact",
        data: {
          ocbId: e.id, //删除的ID
        },
      }).done(
        function (data) {
          if (!data.error.length) {
            message.success("删除成功！");
            this.setState({
              loading: false,
            });
          } else {
            message.warning(data.error[0].message);
          }
          this.contactLists();
        }.bind(this)
      );
    } else {
      this.contactLists();
    }
  },
  //选择主要联系人
  mainContact(record) {
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/customer/updateMainContact",
      data: {
        uid: this.props.data.id,
        ocbId: record.id,
      },
    }).done(
      function (data) {
        if (!data.error.length) {
          message.success("设为主要联系人成功！");
          this.setState({
            loading: false,
          });
        } else {
          message.warning(data.error[0].message);
        }
        this.contactLists();
      }.bind(this)
    );
    this.state.contactList.forEach((item) => {
      item.major = 0;
    });
    record.major = 1;
    // console.log(record);
    this.setState({
      contactList: this.state.contactList,
    });
  },
  //tab2获取联系人详情
  contactLists(ids) {
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/customer/findCustomerContacts",
      data: {
        uid: ids || this.props.data.id, //名称1
      },
      success: function (data) {
        let theArr = [];
        if (data.error.length || data.data.list == "") {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
        } else {
          for (let i = 0; i < data.data.length; i++) {
            let thisdata = data.data[i];
            theArr.push({
              key: i,
              id: thisdata.id,
              name: thisdata.name,
              mobile: thisdata.mobile,
              email: thisdata.email,
              qq: thisdata.qq,
              wechat: thisdata.wechat,
              department: thisdata.department,
              position: thisdata.position,
              major: thisdata.major,
              createTimes: thisdata.createTimes,
              fixedTel: thisdata.fixedTel,
              aname: thisdata.aname,
              cityName:
                (thisdata.provinceName || "") +
                (thisdata.cityName || "") +
                (thisdata.areaName || ""),
            });
          }
        }
        this.setState({
          contactList: theArr,
        });
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },
  //新增
  //tab2新增联系人
  addcontact() {
    this.setState({
      addcontactModul: true,
    });
  },
  componentWillMount() {
    this.contactLists(this.props.data.id);
    this.setState({
      name: this.props.name,
      locationProvince:
        this.props.data.province +
        "-" +
        this.props.data.city +
        "-" +
        this.props.data.area,
      introduction: this.props.data.introduction,
    });
  },
  componentWillReceiveProps(nextProps) {
    // if (nextProps.data.id && nextProps.contactState) {
    if (nextProps.data.id) {
      this.contactLists(nextProps.data.id);
    }
  },
  onOk() {
    if (!this.state.newname) {
      message.warning("请输入渠道名称");
      return;
    }
    this.setState({
      loading: true,
    });
    $.ajax({
      url: globalConfig.context + "/api/admin/customer/updateUserName",
      method: "post",
      data: {
        uid: this.props.data.id,
        userName: this.state.newname,
      },
    }).done(
      function (data) {
        this.setState({
          loading: false,
        });
        if (data.error.length === 0) {
          message.success("恭喜您，更名成功！");
          this.setState({
            visible: "",
            name: this.state.newname,
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  },

  updateDate() {
    const { dataArrar, visible, newintroduction } = this.state;
    if (dataArrar.length === 0 && visible == "city") {
      message.warning("请选择省-市-区");
      return;
    }
    if (!newintroduction && visible == "introduction") {
      message.warning("请输入简介");
      return;
    }
    this.setState({
      loading: true,
    });
    let data = {
      uid: this.props.data.id,
    };
    if (visible == "city") {
      data.province = dataArrar[0] || undefined;
      data.city = dataArrar[1] || undefined;
      data.area = dataArrar[2] || undefined;
    }
    if (visible == "introduction") {
      data.introduction = newintroduction;
    }
    $.ajax({
      url: globalConfig.context + "/api/admin/customer/updateUserDate",
      method: "post",
      data: data,
    }).done(
      function (data) {
        this.setState({
          loading: false,
        });
        if (data.error.length === 0) {
          message.success("恭喜您，更改成功！");
          this.setState({
            visible: "",
          });
          if (visible == "city") {
            this.setState({
              locationProvince: getProvince(
                dataArrar[0],
                dataArrar[1],
                dataArrar[2]
              ),
            });
          }
          if (visible == "introduction") {
            this.setState({
              introduction: newintroduction,
            });
          }
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  },

  render() {
    const { visible } = this.state;
    return (
      <div>
        <div className="clearfix">
          <Alert
            message="注：已保存信息不可修改，可新增正确的信息并设置为主要联系人"
            banner
          />
          <div
            style={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "space-between",
              margin: "30px 60px 30px 0px",
            }}
          >
            <div
              style={{
                fontSize: 14,
                fontWeight: "bold",
              }}
            >
              <div style={{ padding: "5px 0" }}>
                <span>渠道名称：{this.state.name}</span>
                <Button
                  type="primary"
                  style={{ marginLeft: "20px" }}
                  onClick={() => {
                    this.setState({
                      visible: "name",
                      newname: "",
                    });
                  }}
                >
                  渠道更名
                </Button>
              </div>
              <div style={{ padding: "5px 0" }}>
                <span>
                  省-市-区：
                  {this.state.locationProvince}
                </span>
                <Button
                  type="primary"
                  style={{ marginLeft: "20px" }}
                  onClick={() => {
                    this.setState({
                      visible: "city",
                      dataArrar: [],
                    });
                  }}
                >
                  修改
                </Button>
              </div>
              <div style={{ padding: "5px 0" }}>
                <span>渠道简介：{this.state.introduction}</span>
                <Button
                  type="primary"
                  style={{ marginLeft: "20px" }}
                  onClick={() => {
                    this.setState({
                      visible: "introduction",
                      newintroduction: [],
                    });
                  }}
                >
                  修改
                </Button>
              </div>
            </div>
            <Button
              className="ContactsList"
              type="primary"
              onClick={this.addcontact}
            >
              新增联系人
            </Button>
          </div>
        </div>
        <div className="clearfix">
          <Spin spinning={this.state.loading}>
            <Table
              pagination={false}
              columns={this.state.ContactsLists}
              dataSource={this.state.contactList}
            />
          </Spin>
        </div>
        {/* 新增联系人 */}
        <AddContact
          addcontactModul={this.state.addcontactModul}
          uids={this.props.data.id}
          closeFollow={() => {
            this.setState(
              {
                addcontactModul: false,
              },
              () => {
                this.contactLists();
              }
            );
          }}
        />
        {/* 信息修改 */}
        <Modal
          footer={null}
          maskClosable={false}
          width={300}
          title={"信息修改"}
          visible={visible != ""}
          onCancel={() => {
            this.setState({
              visible: "",
            });
          }}
        >
          <div>
            {visible == "name" && (
              <div className="enterpriseNameContent">
                <div className="enterpriseNameItem">
                  <div className="enterpriseNameTitle">更改前:</div>
                  <div className="enterpriseNameValue">{this.state.name}</div>
                </div>
                <div className="enterpriseNameItem">
                  <div className="enterpriseNameTitle">更改后:</div>
                  <div className="enterpriseNameValue">
                    <Input
                      value={this.state.newname}
                      onChange={(e) => {
                        this.setState({
                          newname: e.target.value,
                        });
                      }}
                    />
                  </div>
                </div>
              </div>
            )}
            {visible == "city" && (
              <div className="enterpriseNameContent">
                <div className="enterpriseNameItem">
                  <div className="enterpriseNameTitle">更改前:</div>
                  <div className="enterpriseNameValue">
                    {this.state.locationProvince}
                  </div>
                </div>
                <div className="enterpriseNameItem">
                  <div className="enterpriseNameTitle">更改后:</div>
                  <div className="enterpriseNameValue">
                    <Cascader
                      options={areaSelect()}
                      placeholder="选择城市"
                      onChange={(e, pre) => {
                        this.setState({
                          dataArrar: e,
                        });
                      }}
                    />
                  </div>
                </div>
              </div>
            )}
            {visible == "introduction" && (
              <div className="enterpriseNameContent">
                <div className="enterpriseNameItem">
                  <div className="enterpriseNameTitle">更改前:</div>
                  <div className="enterpriseNameValue">
                    {this.state.introduction}
                  </div>
                </div>
                <div className="enterpriseNameItem">
                  <div className="enterpriseNameTitle">更改后:</div>
                  <div className="enterpriseNameValue">
                    <TextArea
                      style={{ width: "200px" }}
                      value={this.state.newintroduction}
                      onChange={(e) => {
                        this.setState({
                          newintroduction: e.target.value,
                        });
                      }}
                    />
                  </div>
                </div>
              </div>
            )}

            <Popconfirm
              placement="top"
              title="确定要修改吗?"
              onConfirm={(e) => {
                e.stopPropagation();
                visible == "name" ? this.onOk() : this.updateDate();
              }}
              okText="确定"
              cancelText="取消"
            >
              <Button type="primary">确定修改</Button>
            </Popconfirm>
          </div>
        </Modal>
      </div>
    );
  },
});
export default ContactPerson;
