/**
 * 免费在线发放
 */
import React, { Component } from "react";
import { connect } from "dva";
import "../financialWallet.less";
import { withRouter } from "dva/router";
import $modal from "../modal";
import {
  pageComGrantInfoList,
  saveComGrantInfo,
  getComWalletServiceOpenInfo,
  deleteComGrantInfo
} from "../../../services/api";
import {
  Tabs,
  Alert,
  Input,
  Button,
  Table,
  Modal,
  Form,
  Select,
  Drawer,
  Spin
} from "antd";
const { TabPane } = Tabs;
const { Option } = Select;
const formItemLayout = {
  labelCol: {
    xs: { span: 5 },
    sm: { span: 5 }
  },
  wrapperCol: {
    xs: { span: 18 },
    sm: { span: 18 }
  }
};
@connect(state => ({
  profile: state.profile
}))
@withRouter
@Form.create()
export default class FreeDistribution extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // 搜索部分
      searchData: {
        // 表格数据请求参数
        keyword: "", //关键字
        pageNumber: "1", // 页
        pageSize: "10" //条目
      },
      keyword: "", //关键字
      // 表格部分
      tableList: [], // 表格数据
      pagination: {
        //分页数据
        total: 1,
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true
      },
      selectedRows: [], //表格中选中的数组
      selectedRowKeys: [],
      addVisibale: false, //抽屉的显示隐藏
      record: null, //存储基础信息
      basicVisibale: false //基础信息控制
    };
  }
  componentDidMount() {
    this.__getTable(this.state.searchData);
  }
  __getTable(data) {
    pageComGrantInfoList(data).then(res => {
      this.setState({
        tableList: res.data.data,
        pagination: {
          ...this.state.pagination,
          total: res.data.total,
          current: res.data.pageNumber,
          pageSize: res.data.pageSize
        }
      });
    });
  }
  basicSubmitHandle = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log(values);
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.setState({
      submitStatus: true
    });
    this.props.form.validateFields((err, values) => {
      if (!err) {
        getComWalletServiceOpenInfo().then(res => {
          const { isCompleteOpen } = res.data;
          if (isCompleteOpen == 0) {
            $modal(
              "您的企业未开通钱包服务",
              "未开通企业钱包服务，无法进行薪资代发，请先开通企业钱包服务！",
              [
                {
                  text: "去开通",
                  type: "primary",
                  onPress: () => {
                    this.props.history.push("/finance/business-wallet");
                  }
                },
                {
                  text: "取消",
                  onPress: () => {
                    console.log("关闭新增弹窗");
                  }
                }
              ]
            );
          } else {
            saveComGrantInfo(values).then(res => {
              const { comGrantId } = res.data;
              this.props.history.push(
                `/finance/salary-proxy-list?comGrantId=${comGrantId}`
              );
            });
          }
        });
      }
    });
  };
  // 表格渲染
  renderOrderList = () => {
    const columns = [
      {
        title: "代发单号",
        dataIndex: "comGrantId",
        key: "comGrantId"
      },
      {
        title: "标题",
        dataIndex: "title",
        key: "title"
      },
      {
        title: "备注",
        textWrap: "ellipsis",
        dataIndex: "remark",
        key: "remark",
        render: (text, record) => {
          return (
            <span
              style={{
                display: "inline-block",
                maxWidth: 300
              }}
            >
              {text}
            </span>
          );
        }
      },
      {
        title: "创建人",
        dataIndex: "createBy",
        key: "createBy"
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        key: "createTime"
      },
      {
        title: "发放类型",
        dataIndex: "grantType",
        key: "grantType"
      },
      {
        title: "发薪年月",
        dataIndex: "grantYears",
        key: "grantYears",
        render: value => value || "-"
      },
      {
        title: "数据来源",
        dataIndex: "grantDataSource",
        key: "grantDataSource",
        render: value => value || "-"
      },
      {
        title: "状态",
        dataIndex: "allGrantStatusStr",
        key: "allGrantStatusStr",
        render: (text, record) => {
          let color = "";
          //  0  待发放
          // 1  正在发放
          // 2  部分完成
          // 3  全部完成
          if (record.allGrantStatus == "0") {
            color = "orange";
          } else if (record.allGrantStatus == "1") {
            color = "#1890ff";
          } else if (record.allGrantStatus == "2") {
            color = "orange";
          } else if (record.allGrantStatus == "3") {
            color = "green";
          }
          return (
            <div>
              {/* <i style={{display: 'inline-block', marginRight: 5}}>
                
                <span
                  // className="sending_dot"
                  className={
                    record.allGrantStatus === '1' ? 'sending_dot' : ''
                  }
                />
              </i> */}
              <i style={{ width: 20, display: "inline-block" }}>
                <Spin
                  size="small"
                  style={{
                    display: record.allGrantStatus === "1" ? "block" : "none"
                  }}
                />
              </i>
              <span className="status" style={{ color }}>
                {record.allGrantStatusStr}
              </span>
            </div>
          );
        }
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        render: (text, record) => (
          <div>
            {/* 0  待发放
              1  正在发放
              2  部分完成
              3  全部完成 */}
            {/* 基础信息 */}
            {/* {(() => {
              // 正在发放 不可操作
              if (record.allGrantStatus == 1) {
                return (
                  <span
                    style={{
                      color: '#ddd',
                      cursor: 'pointer',
                      marginRight: '20px'
                    }}
                  >基础信息</span>
                );
              } else {
                return (
                  <span
                    style={{
                      color: '#108EE9',
                      cursor: 'pointer',
                      marginRight: '20px'
                    }}
                    onClick={() => {
                      this.setState({
                        record,
                        basicVisibale: true
                      });
                    }}
                  >
                    基础信息
                  </span>
                );
              }
            })()} */}
            {/* 代发列表 */}
            {(() => {
              if (record.allGrantStatus == 1) {
                return (
                  <span
                    style={{
                      color: "#ddd",
                      cursor: "pointer",
                      marginRight: "20px"
                    }}
                  >
                    代发列表
                  </span>
                );
              } else {
                return (
                  <span
                    style={{
                      color: "#108EE9",
                      cursor: "pointer",
                      marginRight: "20px"
                    }}
                    onClick={() => {
                      this.props.history.push(
                        `/finance/salary-proxy-list?comGrantId=${record.comGrantId}`
                      );
                    }}
                  >
                    代发列表
                  </span>
                );
              }
            })()}

            {/* 删除 */}
            {(() => {
              if (record.allGrantStatus == 0 && record.isCanDelete == "1") {
                return (
                  <span
                    style={{
                      color: "#ed4014",
                      cursor: "pointer",
                      marginRight: "20px"
                    }}
                    onClick={() => {
                      $modal(
                        "即将删除在线发放记录",
                        "在线发放记录删除后，不可恢复，是否继续？",
                        [
                          {
                            text: "继续",
                            type: "primary",
                            onPress: () => {
                              console.log(record.comGrantId);
                              deleteComGrantInfo({
                                comGrantId: record.comGrantId
                              }).then(res => {
                                this.__getTable(this.state.searchData);
                              });
                            }
                          },
                          {
                            text: "取消"
                          }
                        ],
                        "warning"
                      );
                    }}
                  >
                    删除
                  </span>
                );
              } else {
                return;
              }
            })()}
          </div>
        )
      }
    ];
    return (
      <div>
        <Table
          dataSource={this.state.tableList}
          columns={columns}
          pagination={this.state.pagination}
          onChange={pagination => {
            const searchData = {
              // 搜索数据
              ...this.state.searchData,
              pageNumber: pagination.current, // 页
              pageSize: pagination.pageSize
            };
            this.setState(
              {
                searchData
              },
              () => {
                this.__getTable(searchData);
              }
            );
          }}
        />
      </div>
    );
  };
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <div className="tab_inner">
          <Alert
            message={
              <div>
                <span>
                  薪资代发：企业可在本页面调取薪酬核算数据，通过企业钱包服务向员工个人钱包中分发工资，代发前，请确定钱包余额是否充足；
                </span>
                <br />
                <span>
                  代发时长：代发订单发起后，系统会逐单处理，发放人数越多，时间越长，请耐心等待；
                </span>
                <br />
                <span>
                  新增代发：若您需要进行薪资代发，请点击“新增代发”按钮进行操作。
                </span>
                <br />
              </div>
            }
            type="warning"
            showIcon
            style={{ marginBottom: "15px" }}
          />
          <label style={{ marginRight: 16 }}>
            关键字：
            <Input
              style={{ width: "214px", marginBottom: "10px" }}
              placeholder="代发单号/代发标题/备注"
              value={this.state.keyword}
              onChange={e => {
                this.setState({
                  keyword: e.target.value
                });
              }}
              maxLength={20}
            />
          </label>
          <Button
            style={{
              marginRight: "16px",
              marginBottom: "16px",
              padding: window && window.innerWidth <= 1366 ? "0 10px" : "0 15px"
            }}
            type="primary"
            onClick={() => {
              const data = {
                ...this.state.searchData,
                keyword: this.state.keyword
              };
              this.setState(
                {
                  searchData: data
                },
                () => {
                  this.__getTable(data);
                }
              );
            }}
          >
            搜索
          </Button>
          <Button
            onClick={() => {
              this.setState(
                {
                  keyword: "",
                  searchData: {
                    keyword: "", //关键字
                    pageNumber: "1", // 页
                    pageSize: "10" //条目
                  }
                },
                () => {
                  this.__getTable(this.state.searchData);
                }
              );
            }}
            style={{
              padding: window && window.innerWidth <= 1366 ? "0 10px" : "0 15px"
            }}
          >
            重置
          </Button>
        </div>
        <Button
          style={{
            marginTop: "16px",
            marginLeft: 20,
            marginBottom: "16px",
            padding: window && window.innerWidth <= 1366 ? "0 10px" : "0 15px"
          }}
          type="primary"
          onClick={() => {
            this.setState({
              addVisibale: true
            });
          }}
        >
          新增代发
        </Button>
        <div className="table_container">{this.renderOrderList()}</div>

        {/* 新增弹窗 */}
        <Modal
          title="新增代发单"
          onOk={this.handleSubmit}
          onCancel={() => {
            this.setState({
              addVisibale: false
            });
          }}
          visible={this.state.addVisibale}
        >
          <div>
            <Form onSubmit={this.handleSubmit}>
              <Form.Item {...formItemLayout} label="标题:">
                {getFieldDecorator("title", {
                  // initialValue: this.state.companyInfo.comName,
                  rules: [
                    {
                      required: true,
                      message: "请输入标题"
                    },
                    {
                      validator: (rule, value, callback) => {
                        if (value && !/^\S{0,20}$/.test(value)) {
                          callback("请输入标题！最大20个字符");
                        } else {
                          callback();
                        }
                      }
                    }
                  ]
                })(<Input placeholder="请输入" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="备注:">
                {getFieldDecorator("remark", {
                  // initialValue: this.state.companyInfo.comName,
                  rules: [
                    {
                      required: true,
                      message: "请输入备注"
                    },
                    {
                      validator: (rule, value, callback) => {
                        if (value && !/^\S{0,300}$/.test(value)) {
                          callback("请输入备注！最大300个字符");
                        } else {
                          callback();
                        }
                      }
                    }
                  ]
                })(<Input.TextArea placeholder="请输入" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="发放类型:">
                {getFieldDecorator("grantType", {
                  initialValue: "1",
                  rules: [
                    {
                      required: true,
                      message: "请下选择发放类型"
                    }
                  ]
                })(
                  <Select>
                    <Option value="1">发放到钱包</Option>
                    {/* <Option disabled value="2">发放到银行卡</Option> */}
                  </Select>
                )}
              </Form.Item>
            </Form>
            <span
              style={{ color: "#FF9900", lineHeight: "20px", marginLeft: 40 }}
            >
              系统会自动关联人员的钱包账户号作为收款账号。
            </span>
          </div>
        </Modal>

        {/* 基础信息抽屉 */}
        <Drawer
          title="基础信息"
          width={720}
          onClose={() => {
            this.setState({
              basicVisibale: false
            });
          }}
          visible={this.state.basicVisibale}
        >
          <div>
            {(() => {
              if (!this.state.record) return;
              return (
                <Form onSubmit={this.basicSubmitHandle}>
                  <Form.Item
                    {...formItemLayout}
                    label="代发单号"
                    className="lao_108"
                  >
                    {getFieldDecorator("comGrantId", {
                      initialValue: this.state.record.comGrantId
                      // rules: [
                      //   {
                      //     max: ,
                      //     message: "限制个字符"
                      //   }
                      // ]
                    })(<Input disabled />)}
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label="标题"
                    className="lao_108"
                  >
                    {getFieldDecorator("title", {
                      initialValue: this.state.record.title,
                      rules: [
                        {
                          max: 20,
                          message: "限制20个字符"
                        }
                      ]
                    })(<Input />)}
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label="备注"
                    className="lao_108"
                  >
                    {getFieldDecorator("remark", {
                      initialValue: this.state.record.remark,
                      rules: [
                        {
                          max: 200,
                          message: "限制200个字符"
                        }
                      ]
                    })(<Input />)}
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label="创建人"
                    className="lao_108"
                  >
                    {getFieldDecorator("createBy", {
                      initialValue: this.state.record.createBy
                    })(<Input disabled />)}
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label="发放类型"
                    className="lao_108"
                  >
                    {getFieldDecorator("grantType", {
                      initialValue: this.state.record.grantType
                    })(<Input disabled />)}
                  </Form.Item>
                  <Form.Item
                    {...formItemLayout}
                    label="状态"
                    className="lao_108"
                  >
                    {getFieldDecorator("allGrantStatus", {
                      initialValue: this.state.record.allGrantStatus
                    })(
                      <Select disabled>
                        <Option value="0">待发放</Option>
                        <Option value="1">正在发放</Option>
                        <Option value="2">部分完成</Option>
                        <Option value="3">全部完成</Option>
                      </Select>
                    )}
                  </Form.Item>
                </Form>
              );
            })()}

            <div
              style={{
                position: "absolute",
                left: 0,
                bottom: 0,
                width: "100%",
                borderTop: "1px solid #e9e9e9",
                padding: "10px 16px",
                background: "#fff",
                textAlign: "right"
              }}
            >
              <Button
                onClick={() => {
                  this.setState({
                    basicVisibale: false
                  });
                }}
                style={{ marginRight: 8 }}
              >
                取消
              </Button>
              {/* <Button onClick={this.basicSubmitHandle} type="primary">
                    确定
                  </Button> */}
            </div>
          </div>
        </Drawer>
      </div>
    );
  }
}
