import React, { Component } from "react";
import { Button, Modal, message, Input, Form, Spin, } from "antd";
import $ from "jquery/src/ajax";
import "./index.less";
import { splitUrl } from '@/tools';
import ImgList from "../imgList";

/**
 * 
 */
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/uploadStopFile",
            data: { sign: "projectStopFile" },
            multiple: true,
            listType: "picture-card",
          }}
          onChange={(infor) => {
            this.handleChange(infor);
          }}
          fileList={fileList}
        />
      </div>
    );
  },

});

class MySuspend extends Component {
  constructor(props) {
    super(props);
    this.state = {
      reason: "", //原因
      orgCodeUrl: [], //附件
      loading: false,
      logList: [], //日志
      emVisible: false, //审核弹窗
      emReason: "", //审核说明
    };
    this.onOks = this.onOks.bind(this);
    this.getOrgCodeUrl = this.getOrgCodeUrl.bind(this);
  }

  componentDidMount() {
    const { rowData, type, again = false } = this.props
    type == "details" && !!rowData && !!rowData.id && this.getLog(rowData.id)
    if (again) {
      this.setState({
        reason: rowData.reason,
        orgCodeUrl: splitUrl(rowData.annexUrl, ",", globalConfig.avatarHost + "/upload"),
      })
    }
  }


  // 日志
  getLog(id) {
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      url: globalConfig.context + "/api/admin/orderProject/projectStopList",
      data: {
        taskStopId: id,
      },
      success: function (data) {
        if (data.error.length === 0) {
          this.setState({
            logList: data.data || [],
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  }
  // 确定
  onOks() {
    const { selectedRowKeys, subClose, title } = this.props
    let annexUrl = []
    if (this.state.orgCodeUrl.length) {
      let annexArr = [];
      this.state.orgCodeUrl.map(function (item) {
        if (
          item.response &&
          item.response.data &&
          item.response.data.length
        ) {
          annexArr.push(item.response.data);
        }
      });
      annexUrl = annexArr.join(",");
    }
    if (typeof annexUrl !== "string") {
      message.warning("请上传附件!");
      return
    }
    if (!this.state.reason) {
      message.warning("请填写原因!");
      return
    }
    if (!this.state.reason.replace(/\s+/g, '')) {
      message.warning("请填写原因!");
      return;
    }
    this.setState({
      loading: true,
    });
    let infor = {
      ids: selectedRowKeys.toString(),
      type: title == "项目重启" ? 1 : 0, //0=项目暂停,1=项目重启
      reason: this.state.reason, //原因
      annexUrl: annexUrl.length ? annexUrl : undefined,//附件,
    }
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/orderProject/addProjectStop",
      data: infor,
    }).done(
      function (data) {
        this.setState({
          loading: false,
        });
        if (!data.error.length) {
          message.success("操作成功!");
          subClose()
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  }
  // 重新
  onAgain() {
    const { subClose, title, rowData } = this.props
    let annexUrl = []
    if (this.state.orgCodeUrl.length) {
      let annexArr = [];
      this.state.orgCodeUrl.map(function (item) {
        if (
          item.response &&
          item.response.data &&
          item.response.data.length
        ) {
          annexArr.push(item.response.data);
        }
      });
      annexUrl = annexArr.join(",");
    }
    if (typeof annexUrl !== "string") {
      message.warning("请上传附件!");
      return
    }
    if (!this.state.reason) {
      message.warning("请填写原因!");
      return
    }
    if (!this.state.reason.replace(/\s+/g, '')) {
      message.warning("请填写原因!");
      return;
    }
    this.setState({
      loading: true,
    });
    let infor = {
      stopId: rowData.id, //暂停编号
      type: title == "项目重启" ? 1 : 0, //0=项目暂停,1=项目重启
      reason: this.state.reason, //原因
      annexUrl: annexUrl.length ? annexUrl : undefined,//附件,
    }
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/orderProject/updateProjectStop",
      data: infor,
    }).done(
      function (data) {
        this.setState({
          loading: false,
        });
        if (!data.error.length) {
          message.success("重新发起成功!");
          subClose()
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  }
  // 图片添加
  getOrgCodeUrl(e) {
    this.setState({ orgCodeUrl: e });
  }
  // 关闭审核弹窗
  emCancel() {
    const { subClose } = this.props
    this.setState({
      emVisible: false,
      emReason: "",
    }, () => {
      subClose()
    })
  }
  // 项目审核
  examineProjectStop(status) {
    if (!this.state.emReason) {
      message.warning("请填写审核说明~");
      return;
    }
    if (!this.state.emReason.replace(/\s+/g, '')) {
      message.warning("请填写审核说明~");
      return;
    }
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "POST",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/orderProject/examineProjectStop",
      data: {
        taskStopId: this.props.rowData.id,
        reason: this.state.emReason,
        status,
      },
    }).done(
      function (data) {
        if (!data.error.length) {
          this.setState({
            loading: false,
          })
          message.success("审核成功!");
          this.emCancel()
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this)
    );
  }

  render() {
    const { visible, title, orderNo, userName, contractNo, isApproved = false,
      subClose, selectedRows, type, reason, annexUrl, rowData,
    } = this.props
    const { logList } = this.state
    const FormItem = Form.Item;
    const formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 20 },
    };
    return (
      <Modal
        maskClosable={false}
        visible={visible}
        width={"700px"}
        title=""
        footer=""
        onCancel={subClose}
      >
        <Spin spinning={this.state.loading}>
          <div className="clearfix">
            <div className="tittle">{title}</div>
            <div style={{ marginLeft: 20 }}>
              <div style={{ marginBottom: 10 }}>
                {type != "details" && "请您确定,是否将"}
                订单号:{orderNo},客户:{userName},合同编号:{contractNo}
                {type != "details" && ("的项目进行" + (title == "项目重启" ? "重启" : "暂停"))}
              </div>
              <div>{title == "项目重启" ? "重启" : "暂停"}项目清单:</div>
              {
                selectedRows.length > 0 && selectedRows.map((item, index) =>
                  <div
                    key={item.id}
                    style={{ marginLeft: 20 }}
                  >{index + 1}{"、" + item.commodityName + "-" + item.id}</div>
                )
              }
            </div>
            <Form>
              <div className="clearfix" style={{ marginTop: 20 }}>
                {
                  type == "details" ?
                    <FormItem
                      {...formItemLayout}
                      label={title == "项目重启" ? "重启原因" : "暂停原因"}
                    >
                      {reason}
                    </FormItem> :
                    <FormItem
                      {...formItemLayout}
                      label={<span><span style={{ color: "red" }}>*</span>{title == "项目重启" ? "重启原因" : "暂停原因"}</span>}
                    >
                      <Input
                        type="textarea"
                        placeholder=""
                        autosize={{ minRows: 3 }}
                        value={this.state.reason}
                        onChange={(e) => {
                          this.setState({ reason: e.target.value });
                        }}
                      />
                      <span>
                        点击“确定{title == "项目重启" ? "重启" : "暂停"}”,
                        审核通过后,项目状态更改为“{title == "项目重启" ? "正常" : "暂停"}”,
                        技术人员将暂停此项目的相关服务!
                      </span>
                    </FormItem>
                }
              </div>
              <div className="clearfix">
                {
                  type == "details" ?
                    <FormItem
                      {...formItemLayout}
                      label="附件"
                    >
                      <ImgList fileList={splitUrl(annexUrl, ",", globalConfig.avatarHost + "/upload")} domId={"details"} />
                    </FormItem> :
                    <FormItem
                      {...formItemLayout}
                      label={<span><span style={{ color: "red" }}>*</span>上传附件</span>}
                    >
                      <PicturesWall
                        fileList={this.getOrgCodeUrl}
                        pictureUrl={this.state.orgCodeUrl}
                      />
                      <p>图片建议:要清晰。</p>
                      <p style={{ color: "red" }}>可上传与客户协议或截图等信息</p>
                    </FormItem>
                }
              </div>
              {
                type != "details" &&
                <div className="clearfix">
                  <FormItem
                    wrapperCol={{ span: 12, offset: 7 }}
                    className="half-middle"
                  >
                    <Button
                      className="submitSave"
                      type="primary"
                      onClick={() => {
                        this.props.again
                          ? this.onAgain()
                          : this.onOks()
                      }}
                    >
                      {
                        this.props.again
                          ? "重新发起"
                          : (title == "项目重启" ? "确定重启" : "确定暂停")
                      }
                    </Button>
                    <Button
                      className="submitSave"
                      type="primary"
                      onClick={subClose}
                    >
                      取消
                    </Button>
                  </FormItem>
                </div>
              }
              {
                // 日志
                type == "details" &&
                <div style={{ marginLeft: 20, marginBottom: 20 }}>
                  {
                    logList.map((item) =>
                      <div key={item.id}>
                        {item.createName + ":" + item.createTimes + " "}
                        <span style={{ color: ["", "green", "red"][item.status], fontWeight: "bold" }}>
                          {" " + ["【发起】", "【通过】", "【拒绝】"][item.status] + " "}
                        </span>
                        {"备注:" + item.reason}
                      </div>
                    )
                  }
                </div>
              }
              {
                !!rowData && rowData.stopStatus == 0 && isApproved &&
                <div className="clearfix">
                  <FormItem
                    wrapperCol={{ span: 12, offset: 10 }}
                    className="half-middle"
                  >
                    <Button
                      type="primary"
                      onClick={() => {
                        this.setState({
                          emVisible: true,
                        })
                      }}
                    >
                      审核
                    </Button>
                  </FormItem>
                </div>
              }
            </Form>
          </div>
        </Spin >
        {
          // 项目审核
          this.state.emVisible &&
          <Modal
            visible={this.state.emVisible}
            width="500px"
            title="项目审核"
            footer=""
            onCancel={() => { this.setState({ emVisible: false }) }}
          >
            <Form>
              <Spin spinning={this.state.loading}>
                <FormItem
                  labelCol={{ span: 5 }}
                  wrapperCol={{ span: 16 }}
                  label={
                    <span>
                      <strong style={{ color: "#f00" }}>*</strong>
                      备注
                    </span>
                  }
                >
                  <Input
                    type="textarea"
                    rows={4}
                    placeholder="请填写审核说明"
                    value={this.state.emReason}
                    onChange={(e) => {
                      this.setState({ emReason: e.target.value });
                    }}
                  />
                </FormItem>
                <FormItem wrapperCol={{ span: 12, offset: 5 }}>
                  <Button
                    type="primary"
                    onClick={() => { this.examineProjectStop(1) }}
                    style={{ marginRight: 20 }}
                  >
                    同意
                  </Button>
                  <Button
                    type="primary"
                    onClick={() => { this.examineProjectStop(2) }}
                    style={{ marginRight: 20 }}
                  >
                    驳回
                  </Button>
                  <Button
                    type="default"
                    onClick={() => { this.setState({ emVisible: false }) }}
                  >
                    取消
                  </Button>
                </FormItem>
              </Spin>
            </Form>
          </Modal>
        }
      </Modal >
    );
  }
}

export default MySuspend;