import React, { Component } from 'react';
import {
  Modal,
  message,
  Input,
  Select,
  Button,
  Form,
  AutoComplete,
} from "antd";
import $ from 'jquery/src/ajax';
import {
  customerType,
  ssalesType,
  qsalesType,
  wsalesType,
} from "@/dataDic.js";

const FormItem = Form.Item;
const { TextArea } = Input;
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
};

class UpdateSales extends Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      channelArr: [],
      upsalesType: false,//修改销售类型弹窗
      channelName: "",
      datas: {},
      channelid: '',
      channelname: '',
    }
  }

  // 关闭弹窗
  close() {
    this.setState({
      upsalesType: false,
      datas: {},
      channelid: '',
      channelname: '',
    })
  }
  // 修改订单销售类型提交
  updateSalesType() {
    const { channelid, channelname, channelName, datas } = this.state;
    const { orderNo, onRefresh = () => { } } = this.props;
    if (datas.salesType == "3" && channelid == "" && !!channelName) {//渠道类型时--如果打开弹窗无更改将直接关闭不调接口
      this.close();
      return
    }
    this.setState({
      loading: true,
    });
    let post = {
      orderNo: orderNo,
      salesType: datas.salesType,//销售类型 
    };
    if (datas.salesType == "3") { //传渠道编号  other里面传渠道名称
      post = Object.assign(post, {
        channelId: channelid,
        other: channelname,
      })
    } else if (datas.salesType == "4" || datas.salesType == "5") { //4,5要传描述
      post = Object.assign(post, {
        other: datas.other,
      })
    }
    $.ajax({
      url: globalConfig.context + "/api/admin/newOrder/updateSalesType",
      method: "post",
      data: post,
    }).done(
      function (data) {
        this.setState({
          loading: false,
        });
        if (!data.error.length) {
          message.success("修改成功！");
          onRefresh(post);
          this.close();
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  }
  // 选中回调
  goSelect(value) {
    let channelid;
    let fwList = this.state.channelArr;
    fwList.map(function (item) {
      if (value == item.name) {
        channelid = item.id;
      }
    });
    this.setState({
      channelname: value,
      channelid: channelid,
    });
  }
  // 渠道名称自动补全
  channelChange(e) {
    this.setState({
      channelName: e
    })
    if (e.length >= 2) {
      this.selectChannel(e);
    }
  }
  // 渠道查询
  selectChannel(e) {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/customer/selectChannelUserList",
      data: {
        name: e,
      },
      success: function (data) {
        let thedata = data.data;
        if (!thedata) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
          thedata = {};
        }
        this.setState({
          channelArr: thedata,
        });
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  }
  // 是否在数组中存在
  isArray(arr, value, title) {
    for (var i = 0; i < arr.length; i++) {
      if (value == arr[i][title]) {
        return true
      }
    }
    return false
  }
  // 点击修改处理
  update() {
    const { updatas } = this.props;
    let defaults = JSON.parse(JSON.stringify(updatas));
    // if (updatas.userType == null && updatas.salesType == null) {//无客户所属类型 无销售类型则可选取所有销售类型
    //   defaults.userType = 2
    // } else {
    //   if (updatas.salesType != null) {
    //     this.isArray(ssalesType, updatas.salesType, "value") && (defaults.userType = 0);//有销售类型（私有客户）
    //     this.isArray(qsalesType, updatas.salesType, "value") && (defaults.userType = 1);//有销售类型（以签单客户）
    //   }
    // }
    // if (updatas.userType == null) {//无客户所属类型时--可让其选择所有销售类型
    //   defaults.userType = 2
    // }
    this.setState({
      datas: defaults,
      channelName: defaults.salesType == "3" ? defaults.other : "",//销售类型为渠道的时候给编辑出的渠道名称赋值
      upsalesType: true,
    })
  }

  render() {
    const { datas } = this.state;
    let cdataSources = this.state.channelArr || [];
    let channeloptions = cdataSources.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    return (
      <span style={{ marginLeft: 10 }}>
        <Button
          type="primary"
          onClick={this.update.bind(this)}
        >修改</Button>
        {
          this.state.upsalesType &&
          <Modal
            title="修改"
            visible={this.state.upsalesType}
            width="600px"
            onOk={this.updateSalesType.bind(this)}
            onCancel={this.close.bind(this)}
          >
            <Form>
              {
                (datas.userType != null && datas.userType != 2) &&
                <FormItem {...formItemLayout} label="客户所属类型">
                  <Select
                    placeholder="请选择客户所属类型"
                    style={{ width: "200px" }}
                    value={datas.userType.toString()}
                    disabled={true}
                  >
                    {customerType.map(function (item) {
                      return (
                        <Select.Option key={item.value}>
                          {item.key}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </FormItem>
              }
              {
                console.log("====", datas.userType)
              }
              <FormItem {...formItemLayout} label="销售类型">
                <Select
                  placeholder="请选择销售类型"
                  style={{ width: "200px" }}
                  value={datas.salesType == null ? undefined : datas.salesType.toString()}
                  onChange={(e) => {
                    this.setState({
                      datas: Object.assign(datas, {
                        salesType: e,
                        other: "",
                        channelName: "",
                      }),
                    });
                  }}
                >
                  {(datas.userType == "0"
                    ? ssalesType : datas.userType == "1"
                      ? qsalesType : datas.userType == "2"
                        ? wsalesType : datas.userType == "3"
                          ? qsalesType : []).map(function (item) {
                            return (
                              <Select.Option key={item.value} disabled={item.value == "5"}>
                                {item.key}
                              </Select.Option>
                            );
                          })}
                </Select>
              </FormItem>
              {
                (datas.salesType == "4" || datas.salesType == "5") &&
                <FormItem {...formItemLayout} label="描述">
                  <TextArea
                    placeholder="请填写描述"
                    style={{ width: 300, height: 80 }}
                    value={datas.other}
                    onChange={(e) => {
                      this.setState({
                        datas: Object.assign(datas, {
                          other: e.target.value,
                        }),
                      });
                    }}
                  />
                </FormItem>
              }
              {
                datas.salesType == "3" &&
                <div className="clearfix">
                  <FormItem {...formItemLayout} label="渠道名称">
                    <AutoComplete
                      className="certain-category-search"
                      dropdownClassName="certain-category-search-dropdown"
                      dropdownMatchSelectWidth={false}
                      dropdownStyle={{ width: 200 }}
                      size="large"
                      style={{ width: "200px" }}
                      dataSource={channeloptions}
                      placeholder="请输入渠道关键字"
                      value={this.state.channelName}
                      onChange={this.channelChange.bind(this)}
                      filterOption={true}
                      onSelect={this.goSelect.bind(this)}
                    >
                      <Input />
                    </AutoComplete>
                    <span className="mandatory">*</span>
                  </FormItem>
                </div>
              }
            </Form>
          </Modal>
        }
      </span>
    )
  }
}
export default UpdateSales;






