/**
 * 薪资发放记录
 */
import React, { Component } from "react";
import "../financialWallet.less";
import { withRouter } from "dva/router";
import {
  InputNumber,
  Alert,
  Input,
  Button,
  Table,
  Modal,
  Form,
  DatePicker,
  Select,
  Popconfirm
} from "antd";
import moment from "moment";
import PTable from "../../../components/Pro/PTable";
import $modal from "../modal";
import PFromUploadFile from "../../../components/Pro/PFormUploadFile";
import {
  saveOffLineGrantRecord,
  deleteOffLineGrantRecord
} from "../../../services/api";
const { Option } = Select;
const { MonthPicker, RangePicker } = DatePicker;
const formItemLayout = {
  labelCol: {
    xs: { span: 6 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 18 },
    sm: { span: 18 }
  }
};
const type = [
  {
    label: "全部",
    value: ""
  },
  {
    label: "线上发放",
    value: "1"
  },
  {
    label: "线下发放",
    value: "2"
  }
];
const mode = [
  {
    label: "全部",
    value: ""
  },
  {
    label: "银行转账",
    value: "1"
  },
  {
    label: "现金",
    value: "2"
  }
];
@withRouter
@Form.create()
export default class DistributionRecord extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      forceUpdate: false,
      pageParm: {
        pageSize: 10,
        pageNumber: 1,
        // grantChannel: "", //类型
        grantMode: "", //方式
        grantYears: ""
      },
      grantYears: "",
      // grantChannel: "",
      grantMode: "",
      addVisibale: false,
      modalTitle: "新增线下发放记录",
      onlySee: false, //是否只读
      currentList: null //当前点击中的数据
    };
  }
  updatePtable() {
    this.setState(
      {
        forceUpdate: true
      },
      () => {
        this.setState({
          forceUpdate: false
        });
      }
    );
  }
  handleSubmit() {
    this.setState({
      submitStatus: true
    });
    this.props.form.validateFields((err, values) => {
      console.log(values);
      if (!err) {
        values.grantYears = moment(values.grantYears).format("YYYY-MM");
        values.grantDate = values["grantDate"].format("YYYY-MM-DD");
        //如果是编辑的页面，需要传id
        if (this.state.currentList) {
          values.comGrantRecordId = this.state.currentList.comGrantRecordId;
        }
        console.log(values);
        saveOffLineGrantRecord(values).then(res => {
          if (res.retType == "0") {
            this.updatePtable();
            this.setState({
              addVisibale: !this.state.addVisibale
            });
            this.props.form.resetFields();
          }
        });
      }
    });
  }
  cancelModal() {
    this.setState({
      onlySee: false,
      addVisibale: !this.state.addVisibale,
      currentList: null
    });
    this.props.form.resetFields();
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: "序号",
        dataIndex: "number",
        key: "number"
      },
      {
        title: "薪资月份",
        dataIndex: "grantYears",
        key: "grantYears"
      },
      {
        title: "发放人数",
        dataIndex: "grantCount",
        key: "grantCount"
      },
      {
        title: "发放日期",
        dataIndex: "grantDate",
        key: "grantDate"
      },
      {
        title: "发放渠道",
        dataIndex: "grantChannelName",
        key: "grantChannelName"
      },
      {
        title: "发放方式",
        dataIndex: "grantModeName",
        key: "grantModeName"
      },
      {
        title: "发放机构名称",
        textWrap: "ellipsis",
        dataIndex: "grantOrgName",
        key: "grantOrgName",
        width:'300px',
        render: (text, record) => {
          return (
            <span
              style={{
                display: "inline-block",
                maxWidth: 300
              }}
            >
              {text}
            </span>
          );
        }
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        render: (text, record) => (
          <div>
            <a
              style={{ marginRight: "10px" }}
              onClick={() => {
                this.setState({
                  onlySee: true,
                  addVisibale: !this.state.addVisibale,
                  currentList: record,
                  modalTitle: "发放记录详情"
                });
                // const { setFieldsValue } = this.props.form;
                // setFieldsValue({ grantVoucherUrl: record.grantVoucherUrl });
              }}
            >
              查看
            </a>
            <a
              style={{ marginRight: "10px" }}
              onClick={() =>
                this.setState({
                  onlySee: false,
                  addVisibale: !this.state.addVisibale,
                  currentList: record,
                  modalTitle: "编辑发放记录"
                })
              }
            >
              编辑
            </a>
            <a
              style={{ color: "red" }}
              onClick={() => {
                $modal(
                  "即将删除薪资代发记录",
                  "薪资代发记录删除后，不可恢复，是否继续？",
                  [
                    {
                      text: "继续",
                      type: "primary",
                      onPress: () => {
                        deleteOffLineGrantRecord({
                          comGrantRecordId: record.comGrantRecordId
                        }).then(res => {
                          if (res.retType == "0") {
                            this.updatePtable();
                          }
                        });
                      }
                    },
                    {
                      text: "取消"
                    }
                  ],
                  "warning"
                );
              }}
            >
              删除
            </a>
          </div>
        )
      }
    ];
    return (
      <div>
        <div className="tab_inner">
          <Alert
            message={
              <div>
                <span>
                线下发放：若您是采用非本平台薪资发放服务的，请点击“新增线下发放记录”按钮，并每月上报发放记录到系统中。
                </span>
              </div>
            }
            type="warning"
            showIcon
            style={{ marginBottom: "15px" }}
          />
          <label style={{ marginRight: 16 }}>
            薪资月份：
            {/* <RangePicker
              placeholder={["开始月份", "结束月份"]}
              format="YYYY-MM"
              value={value}
              // mode={["month", "month"]}
              // mode={["month"]}
              onChange={value => {
                console.log(value);
                this.setState({ value });
              }}
              onPanelChange={(value, mode) => {
                this.setState({
                  startMonth: value[0].format("YYYY-MM"),
                  endMonth: value[1].format("YYYY-MM"),
                  value
                });
              }}
            /> */}
            <MonthPicker
              placeholder="请选择薪资月份"
              format="YYYY-MM"
              value={
                this.state.grantYears
                  ? moment(this.state.grantYears, "YYYY-MM")
                  : null
              }
              onChange={value => {
                this.setState({
                  grantYears: value ? value.format("YYYY-MM") : ""
                });
              }}
            />
          </label>
          {/* <label style={{ marginRight: 16 }}>
            发放渠道：
            <Select
              value={this.state.grantChannel}
              style={{ width: 120 }}
              onChange={value => {
                this.setState({
                  grantChannel: value
                });
              }}
            >
              {type.map(item => {
                return (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                );
              })}
            </Select>
          </label> */}
          <label style={{ marginRight: 16 }}>
            发放方式：
            <Select
              value={this.state.grantMode}
              style={{ width: 120 }}
              onChange={value => {
                this.setState({
                  grantMode: value
                });
              }}
            >
              {mode.map(item => {
                return (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                );
              })}
            </Select>
          </label>
          <Button
            style={{
              marginRight: "16px",
              marginBottom: "16px",
              padding: window && window.innerWidth <= 1366 ? "0 10px" : "0 15px"
            }}
            type="primary"
            onClick={() => {
              const { grantYears, grantMode } = this.state;
              this.setState(
                {
                  pageParm: {
                    ...this.state.pageParm,
                    grantYears,
                    // grantChannel,
                    grantMode
                  }
                },
                () => {
                  console.log(this.state.pageParm);
                  this.updatePtable();
                }
              );
            }}
          >
            搜索
          </Button>
          <Button
            onClick={() => {
              const pageParm = {
                ...this.state.pageParm,
                grantYears: "",
                // grantChannel: "",
                grantMode: ""
              };
              this.setState(
                {
                  pageParm,
                  grantYears: "",
                  // grantChannel: "",
                  grantMode: ""
                },
                () => {
                  this.updatePtable();
                }
              );
            }}
          >
            重置
          </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,
              modalTitle: "新增线下发放记录"
            });
          }}
        >
          新增线下发放记录
        </Button>
        <PTable
          style={{ marginTop: 20, padding: "0px 15px" }}
          columns={columns}
          url="pageComGrantRecordList"
          pageParm={this.state.pageParm}
          forceUpdate={this.state.forceUpdate}
        />
        {/* 新增/编辑/查看发放记录 */}
        <Modal
          title={this.state.modalTitle}
          // onOk={() => this.handleSubmit()}
          onCancel={() => this.cancelModal()}
          visible={this.state.addVisibale}
          footer={
            !this.state.onlySee
              ? [
                  <Button key="back" onClick={() => this.cancelModal()}>
                    取消
                  </Button>,
                  <Button
                    key="submit"
                    type="primary"
                    onClick={() => this.handleSubmit()}
                  >
                    确定
                  </Button>
                ]
              : ""
          }
        >
          <Form onSubmit={() => this.handleSubmit()}>
            <Form.Item {...formItemLayout} label="薪资月份:">
              {getFieldDecorator("grantYears", {
                initialValue: this.state.currentList
                  ? moment(this.state.currentList.grantYears, "YYYY-MM")
                  : "",
                rules: [
                  {
                    required: true,
                    message: "请选择薪资月份"
                  }
                ]
              })(
                <MonthPicker
                  placeholder="请选择薪资月份"
                  format="YYYY-MM"
                  disabled={this.state.onlySee}
                  disabledDate={current => {
                    return current && current > moment(parseInt(sessionStorage.getItem('requestDate'))).endOf("day");
                  }}
                />
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="发放人数:">
              {getFieldDecorator("grantCount", {
                initialValue: this.state.currentList
                  ? this.state.currentList.grantCount
                  : "",
                rules: [
                  {
                    required: true,
                    message: "请输入发放人数"
                  }
                ]
              })(<InputNumber min={0} disabled={this.state.onlySee} />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="发放日期:">
              {getFieldDecorator("grantDate", {
                initialValue: this.state.currentList
                  ? moment(this.state.currentList.grantDate, "YYYY-MM-DD")
                  : "",
                rules: [
                  {
                    required: true,
                    message: "请选择发放日期"
                  }
                ]
              })(
                <DatePicker
                  format="YYYY-MM-DD"
                  disabled={this.state.onlySee}
                  disabledDate={current => {
                    return current && current > moment(parseInt(sessionStorage.getItem('requestDate'))).endOf("day");
                  }}
                />
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="发放方式:">
              {getFieldDecorator("grantMode", {
                initialValue: this.state.currentList
                  ? this.state.currentList.grantMode
                  : "",
                rules: [
                  {
                    required: true,
                    message: "请选择发放方式"
                  }
                ]
              })(
                <Select style={{ width: 120 }} disabled={this.state.onlySee}>
                  {mode.map(item => {
                    if (item.value) {
                      return (
                        <Option value={item.value} key={item.value}>
                          {item.label}
                        </Option>
                      );
                    }
                  })}
                </Select>
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="发放机构名称:"
              extra={
                <span style={{ color: "#FF9900" }}>
                  若为现金发放，则默认为本公司全称。
                </span>
              }
            >
              {getFieldDecorator("grantOrgName", {
                initialValue: this.state.currentList
                  ? this.state.currentList.grantOrgName
                  : "",
                rules: [
                  {
                    required: true,
                    message: "请输入发放机构名称"
                  }
                ]
              })(
                <Input
                  placeholder="请输入"
                  maxLength={50}
                  disabled={this.state.onlySee}
                />
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="发放凭证文件:">
              {getFieldDecorator("grantVoucherUrl", {
                initialValue: this.state.currentList
                  ? this.state.currentList.grantVoucherUrl
                  : "",
                rules: [
                  {
                    required: true,
                    message: "请上传发放凭证文件"
                  }
                ]
              })(
                <PFromUploadFile
                  key={Math.random()}
                  type={["doc", "docx", "pdf", "rar", "zip"]}
                  disabled={this.state.onlySee}
                  num={1}
                />
              )}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
