import React from "react";
import { Modal, Spin, TreeSelect, Form, Button, Input, Select, message, AutoComplete } from "antd";
import $ from "jquery/src/ajax";
import './index.less'
import { newTreeData } from "@/tools";

const Operation = React.createClass({
  getInitialState() {
    return {
      confirmLoading: false,
      levelData: [],
    };
  },

  componentDidMount() {
    const { levelData, lev, id } = this.props
    !!id && this.getDetails(id)
    this.setState({
      levelData: newTreeData(levelData, lev),
    })
  },

  // 巴详情接口
  getDetails(id) {
    this.setState({
      confirmLoading: true
    })
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/amb/details",
      data: { id },
      success: function (data) {
        this.setState({
          confirmLoading: false,
        });
        let thedata = data.data;
        if (data.error.length === 0) {
          this.setState({
            parentId: thedata.parentId,
            name: thedata.name,
            leader: thedata.leader,
            financeId: thedata.financeId,
            accountant: thedata.accountant,
            remarks: thedata.remarks,
            auto1: thedata.leaderName,
            auto2: thedata.financeName,
            auto3: thedata.accountantName,
          })
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          confirmLoading: false
        })
      }.bind(this)
    );
  },
  // 巴主查询
  supervisor(e, role) {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/customer/listAdminByName",
      data: {
        adminName: e,
      },
      success: function (data) {
        let thedata = data.data;
        if (!thedata) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
          thedata = {};
        }
        if (role == "bz") {
          this.setState({
            customerArr1: thedata,
          });
        } else if (role == "cw") {
          this.setState({
            customerArr2: thedata,
          });
        } else if (role == "kj") {
          this.setState({
            customerArr3: thedata,
          });
        }
      }.bind(this),
    }).always(
      function () {

      }.bind(this)
    );
  },
  // 巴主输入触发
  httpChange1(e) {
    let str = e.trim()
    if (str.length >= 1) {
      this.supervisor(str, "bz");
    }
    this.setState({
      auto1: str,
    });
  },
  // 巴主选中
  selectAuto1(value, options) {
    let leaderid = "";
    let contactLists = this.state.customerArr1 || [];
    if (value) {
      contactLists.map(function (item) {
        if (item.name == value.toString()) {
          leaderid = item.id
        }
      });
    }
    this.setState({
      auto1: value,
      leader: leaderid,
    });
  },
  // 巴主失去焦点时间
  blurChange1(e) {
    let leaderid = "";
    let contactLists = this.state.customerArr1 || [];
    if (e) {
      contactLists.map(function (item) {
        if (item.name == e.toString()) {
          leaderid = item.id
        }
      });
    }
    this.setState({
      leader: leaderid,
    });
  },
  // 财务输入触发
  httpChange2(e) {
    let str = e.trim()
    if (str.length >= 1) {
      this.supervisor(str, "cw");
    }
    this.setState({
      auto2: str,
    });
  },
  // 财务选中
  selectAuto2(value, options) {
    let financeid = "";
    let contactLists = this.state.customerArr2 || [];
    if (value) {
      contactLists.map(function (item) {
        if (item.name == value.toString()) {
          financeid = item.id
        }
      });
    }
    this.setState({
      auto2: value,
      financeId: financeid,
    });
  },
  // 财务失去焦点时间
  blurChange2(e) {
    let financeid = "";
    let contactLists = this.state.customerArr2 || [];
    if (e) {
      contactLists.map(function (item) {
        if (item.name == e.toString()) {
          financeid = item.id
        }
      });
    }
    this.setState({
      financeId: financeid,
    });
  },
  // 财务输入触发
  httpChange3(e) {
    let str = e.trim()
    if (str.length >= 1) {
      this.supervisor(str, "kj");
    }
    this.setState({
      auto3: str,
    });
  },
  // 会计选中
  selectAuto3(value, options) {
    let accountant = "";
    let contactLists = this.state.customerArr3 || [];
    if (value) {
      contactLists.map(function (item) {
        if (item.name == value.toString()) {
          accountant = item.id
        }
      });
    }
    this.setState({
      auto3: value,
      accountant: accountant,
    });
  },
  // 会计失去焦点时间
  blurChange3(e) {
    let accountant = "";
    let contactLists = this.state.customerArr3 || [];
    if (e) {
      contactLists.map(function (item) {
        if (item.name == e.toString()) {
          accountant = item.id
        }
      });
    }
    this.setState({
      accountant: accountant,
    });
  },
  // 新建巴
  addSubmit() {
    if (this.state.parentId === undefined || !this.state.parentId) {
      message.warning("请选择上级部门！");
      return
    }
    if (!this.state.name) {
      message.warning("请填写巴名称！");
      return
    }
    if (this.state.leader === undefined || !this.state.leader) {
      message.warning("请设置巴主！");
      return
    }
    if (this.state.financeId === undefined || !this.state.financeId) {
      message.warning("请选择财务负责人！");
      return
    }
    if (this.state.accountant === undefined || !this.state.accountant) {
      message.warning("请选择会计负责人！");
      return
    }
    this.setState({
      confirmLoading: true
    })
    let data = {
      parentId: this.state.parentId,
      name: this.state.name,
      leader: this.state.leader,
      financeId: this.state.financeId,
      accountant: this.state.accountant,
      remarks: this.state.remarks,
    }
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/amb/add",
      data,
      success: function (data) {
        if (data.error.length === 0) {
          message.success("保存成功！");
          this.props.handleCancel();
        } else {
          message.warning(data.error[0].message);
        }
        this.setState({
          confirmLoading: false,
        });
      }.bind(this),
    }).always(
      function () {
        this.setState({
          confirmLoading: false,
        });
      }.bind(this)
    );
  },
  // 编辑巴
  editSubmit() {
    if (this.state.parentId === undefined || !this.state.parentId) {
      message.warning("请选择上级部门！");
      return
    }
    if (!this.state.name) {
      message.warning("请填写巴名称！");
      return
    }
    if (this.state.leader === undefined || !this.state.leader) {
      message.warning("请设置巴主！");
      return
    }
    if (this.state.financeId === undefined || !this.state.financeId) {
      message.warning("请选择财务负责人！");
      return
    }
    if (this.state.accountant === undefined || !this.state.accountant) {
      message.warning("请选择会计负责人！");
      return
    }
    this.setState({
      confirmLoading: true
    })
    let data = {
      id: this.props.id,
      parentId: this.state.parentId,
      name: this.state.name,
      leader: this.state.leader,
      financeId: this.state.financeId,
      accountant: this.state.accountant,
      remarks: this.state.remarks,
    }
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/amb/update",
      data,
      success: function (data) {
        if (data.error.length === 0) {
          message.success("保存成功！");
          this.props.handleCancel();
        } else {
          message.warning(data.error[0].message);
        }
        this.setState({
          confirmLoading: false,
        });
      }.bind(this),
    }).always(
      function () {
        this.setState({
          confirmLoading: false,
        });
      }.bind(this)
    );
  },


  render() {
    const { confirmLoading, levelData } = this.state
    const { visible, } = this.props;
    const FormItem = Form.Item;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };
    const dataSources1 = this.state.customerArr1 || [];
    const options1 = dataSources1.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    const dataSources2 = this.state.customerArr2 || [];
    const options2 = dataSources2.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    const dataSources3 = this.state.customerArr3 || [];
    const options3 = dataSources3.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    return (
      <Modal
        maskClosable={false}
        width="600px"
        title={visible == "add"
          ? "新增巴" : visible == "edit"
            ? "编辑巴" : ""}
        visible={visible != ""}
        footer=""
        onCancel={this.props.handleCancel}
      >
        <Spin spinning={confirmLoading}>
          <div>
            <Form
              layout="horizontal"
            >
              <div className="clearfix">
                <FormItem
                  className="mid-item"
                  {...formItemLayout}
                  label={<span><span className="mandatory">*</span>上级部门</span>}
                >
                  <TreeSelect
                    style={{ width: 250 }}
                    value={this.state.parentId}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    treeData={levelData}
                    placeholder="请选择上级部门"
                    showSearch
                    treeNodeFilterProp="title"
                    onChange={(e) => {
                      this.setState({
                        parentId: e,
                      });
                    }}
                  />
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem
                  className="mid-item"
                  {...formItemLayout}
                  label={<span><span className="mandatory">*</span>巴名称</span>}
                >
                  <Input
                    placeholder="请填写巴名称"
                    style={{ width: "250px" }}
                    value={this.state.name}
                    onChange={(e) => {
                      this.setState({ name: e.target.value });
                    }}
                  />
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem
                  className="mid-item"
                  {...formItemLayout}
                  label={<span><span className="mandatory">*</span>巴主</span>}
                >
                  <AutoComplete
                    className="certain-category-search"
                    dropdownClassName="certain-category-search-dropdown"
                    dropdownMatchSelectWidth={false}
                    style={{ width: "250px" }}
                    dataSource={options1}
                    placeholder='输入巴主名称'
                    value={this.state.auto1}
                    onChange={this.httpChange1}
                    filterOption={true}
                    onBlur={this.blurChange1}
                    onSelect={this.selectAuto1}
                  >
                    <Input />
                  </AutoComplete>
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem
                  className="mid-item"
                  {...formItemLayout}
                  label={<span><span className="mandatory">*</span>财务负责人</span>}
                >
                  <AutoComplete
                    className="certain-category-search"
                    dropdownClassName="certain-category-search-dropdown"
                    dropdownMatchSelectWidth={false}
                    style={{ width: "250px" }}
                    dataSource={options2}
                    placeholder='输入财务负责人名称'
                    value={this.state.auto2}
                    onChange={this.httpChange2}
                    filterOption={true}
                    onBlur={this.blurChange2}
                    onSelect={this.selectAuto2}
                  >
                    <Input />
                  </AutoComplete>
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem
                  className="mid-item"
                  {...formItemLayout}
                  label={<span><span className="mandatory">*</span>会计负责人</span>}
                >
                  <AutoComplete
                    className="certain-category-search"
                    dropdownClassName="certain-category-search-dropdown"
                    dropdownMatchSelectWidth={false}
                    style={{ width: "250px" }}
                    dataSource={options3}
                    placeholder='输入会计负责人名称'
                    value={this.state.auto3}
                    onChange={this.httpChange3}
                    filterOption={true}
                    onBlur={this.blurChange3}
                    onSelect={this.selectAuto3}
                  >
                    <Input />
                  </AutoComplete>
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem
                  className="mid-item"
                  {...formItemLayout}
                  label={<span>备注巴说明</span>}
                >
                  <Input
                    type="textarea"
                    placeholder="备注说明"
                    style={{ width: "250px" }}
                    autosize={{ minRows: 3 }}
                    value={this.state.remarks}
                    onChange={(e) => {
                      this.setState({ remarks: e.target.value });
                    }}
                  />
                </FormItem>
              </div>
              <FormItem wrapperCol={{ span: 12, offset: 8 }}>
                <Button
                  type="primary"
                  onClick={!!this.props.id ? this.editSubmit : this.addSubmit}
                  style={{ marginRight: "50px" }}
                >
                  保存
                </Button>
                <Button
                  type="ghost"
                  onClick={this.props.handleCancel}>
                  取消
                </Button>
              </FormItem>
            </Form>
          </div>
        </Spin>
      </Modal >
    );
  },
});

export default Operation;
