import React, { Component } from "react";
import { AutoComplete, Button, Form, Input, message, Modal, Select, Spin } from "antd";
import $ from "jquery";
import ImgList from "../../common/imgList";
import { splitUrl } from "../../tools";

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
};

const PicturesWall = React.createClass({
  getInitialState() {
    return {
      previewVisible: false,
      previewImage: "",
      fileList: this.props.pictureUrl,
    };
  },
  getDefaultProps() {
    return {
      changeClick: this.modifyChange,
    };
  },
  handleCancel() {
    this.setState({ previewVisible: false });
  },
  handlePreview(file) {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  },
  handleChange(info) {
    let fileList = info.fileList;
    this.setState({ fileList });
    this.props.fileList(fileList);
  },
  componentWillReceiveProps(nextProps) {
    this.state.fileList = nextProps.pictureUrl;
  },
  render() {
    const { fileList } = this.state;
    return (
      <div style={{ display: "inline-block" }}>
        <ImgList
          domId={this.props.domId}
          uploadConfig={{
            action: globalConfig.context + "/api/admin/orderProject/uploadMemberFile",
            data: { sign: "order_invoice_file" },
            multiple: true,
            listType: "picture-card",
          }}
          onChange={(infor) => {
            this.handleChange(infor);
          }}
          fileList={fileList}
        />
      </div>
    );
  },
});

class ProjectOperationVip extends Component {
  constructor(props) {
    super(props);
    this.state = {
      commodityName: '',
      commodityQuantity: '',
      patentType: 0,
      officialCost: '',
      costReduction: '',
      commodityPrice: '',
      main: '',
      taskComment: '',
      declarationBatch: '',
      ifCertificationFee: '',
      displayFees: "none",
      customerArr: [],
      patentTypeList: [],
      loading: false,
      patentTransfer: props.dataInfor ? props.dataInfor.patentTransfer : 0, //收否为专利转让 0 否 1 是
      orgCodeUrl: [],
    }
    this.onSubmit = this.onSubmit.bind(this);
    this.httpChange = this.httpChange.bind(this);
    this.selectAuto = this.selectAuto.bind(this);
    this.setValue = this.setValue.bind(this);
    this.getOrgCodeUrl = this.getOrgCodeUrl.bind(this);
  }

  componentDidMount() {
    this.setValue();
  }

  setValue() {
    const { dataInfor } = this.props;
    if (!(dataInfor && Object.keys(dataInfor).length > 0)) { return; }
    this.setState({
      fid: dataInfor.id,
      commodityId: dataInfor.commodityId, //项目ID
      commodityName: dataInfor.commodityName, //项目名称
      commodityQuantity: dataInfor.commodityQuantity, // 数量
      memberType: dataInfor.memberType.toString(),// 付款情况
      taskComment: dataInfor.taskComment, // 备注
      orgCodeUrl: dataInfor.pictureUrl ? splitUrl(dataInfor.pictureUrl, ",", globalConfig.avatarHost + "/upload") : [],// 附件
    });
  }
  //
  getOrgCodeUrl(e) {
    this.setState({ orgCodeUrl: e });
  }
  // 新建会员项目
  onSubmit() {

    let pictureUrl = [];
    if (this.state.orgCodeUrl.length) {
      let picArr = [];
      this.state.orgCodeUrl.map(function (item) {
        if (
          item.response &&
          item.response.data &&
          item.response.data.length
        ) {
          picArr.push(item.response.data);
        }
      });
      pictureUrl = picArr.join(",");
    }

    if (this.state.commodityId === undefined || !this.state.commodityId) {
      message.warning("服务名称不匹配!");
      return
    }
    let reg = /^([0]|[1-9][0-9]*)$/;
    if (
      !this.state.commodityQuantity ||
      !reg.test(this.state.commodityQuantity)
    ) {
      message.warning("请输入正确商品数量!");
      return
    }
    if (this.state.memberType === undefined) {
      message.warning("请选择付款情况!");
      return
    }
    if (this.state.memberType == "1" || this.state.memberType == "2") {
      if (typeof pictureUrl !== "string") {
        message.warning("请上传附件!");
        return
      }
    }
    this.setState({
      loading: true,
    });
    let infor = {
      orderNo: this.props.orderNo, //订单编号
      commodityId: this.state.commodityId, //项目编号
      commodityName: this.state.commodityName, //项目名称
      commodityQuantity: this.state.commodityQuantity, //商品数量
      commodityPrice: 0, //签单总价
      taskComment: this.state.taskComment, //服务说明
      memberType: this.state.memberType,//会员付款状态
      pictureUrl: pictureUrl.length ? pictureUrl : "",//附件
    }
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/orderProject/addMemberProject",
      data: infor,
    }).done(
      function (data) {
        this.setState({
          loading: false,
        });
        if (!data.error.length) {
          Modal.success({
            title: '保存成功!',
            content: (
              <div>
                已提出会员项目申请!请在
                <span style={{ color: "red" }}>“订单管理-我的会员项目“</span>
                跟进查看会员项目的审核状态,审核通过,即表示添加会员项目完成!!!
              </div>),
          });
          this.props.onCancel();
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  }
  // 修改会员项目
  onChange() {

    let pictureUrl = [];
    if (this.state.orgCodeUrl.length) {
      let picArr = [];
      this.state.orgCodeUrl.map(function (item) {
        if (
          item.response &&
          item.response.data &&
          item.response.data.length
        ) {
          picArr.push(item.response.data);
        }
      });
      pictureUrl = picArr.join(",");
    }

    if (this.state.commodityId === undefined || !this.state.commodityId) {
      message.warning("服务名称不匹配!");
      return
    }
    let reg = /^([0]|[1-9][0-9]*)$/;
    if (
      !this.state.commodityQuantity ||
      !reg.test(this.state.commodityQuantity)
    ) {
      message.warning("请输入正确商品数量!");
      return false;
    }
    if (this.state.memberType === undefined) {
      message.warning("请选择付款情况!");
      return
    }
    if (this.state.memberType == "1" || this.state.memberType == "2") {
      if (typeof pictureUrl !== "string") {
        message.warning("请上传附件!");
        return
      }
    }
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/orderProject/updateMemberProject",
      data: {
        id: this.state.fid, //任务ID
        commodityId: this.state.commodityId, //项目ID
        commodityName: this.state.commodityName, //项目名称
        orderNo: this.props.orderNo, //订单编号
        commodityQuantity: this.state.commodityQuantity, //数量
        taskComment: this.state.taskComment, //备注
        memberType: this.state.memberType,//会员付款状态
        pictureUrl: pictureUrl.length ? pictureUrl : "",//附件
      },
    }).done(
      function (data) {
        this.setState({
          loading: false,
        });
        if (!data.error.length) {
          message.success("保存成功!");
          this.props.onCancel();
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  }

  httpChange(e) {
    this.setState({
      commodityName: e,
    });
    if (e.length >= 1) {
      this.supervisor(e);
    }
  }
  //加载(自动补全)
  supervisor(e) {
    //服务名称自动补全
    let api = "/api/admin/order/getBusinessProjectByName";
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + api,
      data: {
        businessName: e,
        cname: "高新会员服务",
      },
      success: function (data) {
        let thedata = data.data;
        if (!thedata) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
          thedata = {};
        }
        this.setState({
          customerArr: thedata,
        });
      }.bind(this),
    }).always(
      function () {

      }.bind(this)
    );
  }
  //上级主管输入框失去焦点是判断客户是否存在
  selectAuto(value) {
    const { customerArr } = this.state;
    const newdataSources = JSON.stringify(customerArr) == "{}" ? [] : customerArr;
    this.setState({
      commodityName: value,
      commodityId: newdataSources.find((item) => item.bname == value).id,
    });
  }

  render() {
    let options = this.state.customerArr.map((group, index) => (
      <Select.Option key={index} value={group.bname}>
        {group.bname}
      </Select.Option>
    ));
    const { readOnly } = this.props;
    return (
      <Modal
        maskClosable={false}
        visible={this.props.visible}
        onOk={this.props.onCancel}
        onCancel={this.props.onCancel}
        width="900px"
        title={readOnly ? "会员详情" : !this.state.fid ? "添加会员项目" : "编辑会员项目"}
        footer=""
        className="admin-desc-content"
      >
        <Form
          layout="horizontal"
        >
          <Spin spinning={this.state.loading}>
            <div className="clearfix">
              <FormItem
                className="half-item"
                {...formItemLayout}
                label="服务名称"
              >
                {readOnly ? this.state.commodityName :
                  <AutoComplete
                    className="certain-category-search"
                    dropdownClassName="certain-category-search-dropdown"
                    dropdownMatchSelectWidth={false}
                    style={{ width: "200px" }}
                    dataSource={options}
                    placeholder="输入服务名称"
                    value={this.state.commodityName}
                    onChange={this.httpChange}
                    filterOption={true}
                    onSelect={this.selectAuto}
                  >
                    <Input />
                  </AutoComplete>}
                <span className="mandatory">*</span>
              </FormItem>
              <FormItem
                className="half-item"
                {...formItemLayout}
                label="服务数量"
              >
                {readOnly ? this.state.commodityQuantity :
                  <Input
                    placeholder="请输入服务数量"
                    value={this.state.commodityQuantity}
                    style={{ width: "200px" }}
                    onChange={(e) => {
                      this.setState({ commodityQuantity: e.target.value });
                    }}
                    ref="commodityQuantity"
                  />}
                <span className="mandatory">*</span>
              </FormItem>
              <div
                style={{
                  marginTop: "33px",
                  color: "red",
                  textAlign: "right",
                  position: "relative",
                  top: "-8",
                  left: "0"
                }}
              >如会员项目,服务一年,请填写1,服务二年,请填写2,依次类推</div>
              <FormItem
                className="half-item"
                {...formItemLayout}
                label="付款情况"
              >
                {readOnly ?
                  [
                    { value: "0", key: "已付会员节点全款" },
                    { value: "1", key: "已付部分期款,需特批" },
                    { value: "2", key: "未付款,需特批" }][this.state.memberType] :
                  <Select
                    placeholder="选择付款情况"
                    style={{ width: "200px" }}
                    value={this.state.memberType}
                    onChange={(e) => {
                      this.setState({ memberType: e });
                    }}
                  >
                    {[
                      { value: "0", key: "已付会员节点全款" },
                      { value: "1", key: "已付部分期款,需特批" },
                      { value: "2", key: "未付款,需特批" }].map(function (item) {
                        return (
                          <Select.Option key={item.value}>
                            {item.key}
                          </Select.Option>
                        );
                      })}
                  </Select>}
                <span className="mandatory">*</span>
              </FormItem>
              {
                (this.state.memberType == "1" || this.state.memberType == "2") &&
                <div className="clearfix">
                  <FormItem
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    label="上传附件"
                  >
                    <PicturesWall
                      domId={'vip'}
                      fileList={this.getOrgCodeUrl}
                      pictureUrl={this.state.orgCodeUrl}
                    />
                    <span className="mandatory">*</span>
                  </FormItem>
                  <div style={{ color: "red", marginLeft: 144, marginBottom: 15 }}>
                    特批需上传附件图,请上传客户同意我方继续服务并安排给我司付款的聊天记录截图,
                    <p>若没有客户同意继续服务及会安排付款的截图,特派流程将无法走下去,以免造成派单耽搁</p>
                  </div>
                </div>
              }
              <div className="clearfix">
                <FormItem
                  labelCol={{ span: 4 }}
                  wrapperCol={{ span: 16 }}
                  label="项目说明"
                >
                  {readOnly ? this.state.taskComment :
                    <Input
                      type="textarea"
                      placeholder="如:派2022年会员服务,总会员服务三年,客户付款情况说明"
                      autosize={{ minRows: 4 }}
                      value={this.state.taskComment}
                      onChange={(e) => {
                        this.setState({ taskComment: e.target.value });
                      }}
                    />}
                </FormItem>
                <div style={{ color: "red", marginLeft: 144 }}>
                  请详细说明项目服务时间,总服务时间及付款情况,如:<span style={{ color: "#333" }}>派2022年会员服务,总会员服务三年,客户付款情况说明</span>
                  <p>未付款时,需进行特批审核,请详细说明预计付款时间等详细情况</p>
                </div>
              </div>
              {readOnly ? null : <FormItem
                wrapperCol={{ span: 12, offset: 4 }}
                className="half-middle"
              >
                <Button
                  className="submitSave"
                  type="primary"
                  onClick={() => {
                    if (!this.state.fid) {
                      this.onSubmit()
                    } else {
                      this.onChange()
                    }
                  }}
                >
                  保存
                </Button>
                <Button
                  className="submitSave"
                  type="ghost"
                  onClick={this.props.onCancel}
                >
                  取消
                </Button>
              </FormItem>}
            </div>
          </Spin>
        </Form>
      </Modal>
    )
  }
}

export default ProjectOperationVip;