import React from "react";
import { WeaDialog, WeaTable, WeaTop } from "ecCom";
import { WeaForm } from "comsMobx";
import { Button, message } from "antd";
import SysForm from "./components/sysForm";
import { sysConditions } from "./conditions";
import * as API from "../../apis/sysconfig";
import "./index.less";
import _ from "lodash";

export default class SysConfig extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      form: new WeaForm(),
      dataSource: [],
      columns: [],
      loading: {
        query: false,
        add: false,
        update: false
      },
      pageInfo: {
        current: 1,
        pageSize: 10,
        total: 10
      },
      modalProps: {
        visible: false,
        title: "新增配置项",
        formId: ""
      }
    };
  }

  componentDidMount() {
    this.state.form.initFormFields(sysConditions);
    this.getSysList();
  }

  getSysList = () => {
    const { pageInfo, loading } = this.state;
    const payload = {
      ...pageInfo
    };
    this.setState({ loading: { ...loading, query: true } });
    API.getSysList(payload).then(({ status, data }) => {
      this.setState({ loading: { ...loading, query: false } });
      if (status && !_.isEmpty(data)) {
        const { columns, list: dataSource, total, pageSize, pageNum: current } = data;
        this.setState({
          columns: [...columns, {
            title: "操作",
            key: "operation",
            render: (text, record) => (
              <span>
                <a href="javascript:void(0);" onClick={() => this.setState({
                  modalProps: {
                    ...this.state.modalProps,
                    visible: true,
                    title: "编辑配置项",
                    formId: record.id
                  }
                }, () => this.getSysDetail(record.id))}>编辑</a>
              </span>
            )
          }],
          dataSource,
          pageInfo: { ...pageInfo, total, pageSize, current }
        });
      }
    });
  };
  getSysDetail = (id) => {
    const { form } = this.state;
    const payload = { id };
    API.getSysDetail(payload).then(({ status, data, errormsg }) => {
      if (status) {
        const [fieldItems] = sysConditions;
        fieldItems.items = _.map(fieldItems.items, it => {
          const { domkey } = it;
          return {
            ...it,
            value: data[domkey[0]]
          };
        });
        form.initFormFields(sysConditions);
      } else {
        message.error(errormsg);
      }
    });
  };
  sysSave = (payload) => {
    const { loading, modalProps, form } = this.state;
    this.setState({ loading: { ...loading, add: true } });
    API.sysSave(payload).then(({ status, errormsg }) => {
      this.setState({ loading: { ...loading, add: false } });
      if (status) {
        message.success("新增成功");
        this.setState({ modalProps: { ...modalProps, visible: false, title: "新增配置项", formId: "" } }, () => {
          this.getSysList();
          form.reset();
        });
      } else {
        message.error(errormsg || "新增失败");
      }
    });
  };
  sysUpdate = (payload) => {
    const { loading, modalProps, form } = this.state;
    this.setState({ loading: { ...loading, update: true } });
    API.sysUpdate(payload).then(({ status, errormsg }) => {
      this.setState({ loading: { ...loading, update: false } });
      if (status) {
        message.success("更新成功");
        this.setState({ modalProps: { ...modalProps, visible: false, title: "新增配置项", formId: "" } }, () => {
          this.getSysList();
          form.reset();
        });
      } else {
        message.error(errormsg || "更新失败");
      }
    });
  };

  handleSubmit = () => {
    const { form, modalProps } = this.state;
    const { formId } = modalProps;
    form.validateForm().then(f => {
      if (f.isValid) {
        const params = form.getFormParams();
        !formId ? this.sysSave(params) : this.sysUpdate({ ...params, id: formId });
      } else {
        f.showErrors();
        this.forceUpdate();
      }
    });
  };

  render() {
    const { dataSource, columns, pageInfo, modalProps, form, loading } = this.state;
    const btns = [
      <Button type="primary" onClick={() => this.setState({ modalProps: { ...modalProps, visible: true } }, () => {
        form.reset();
      })}>新增</Button>
    ];
    const pagination = {
      total: pageInfo.total,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onShowSizeChange: (current, pageSize) => {
        this.setState({ pageInfo: { ...pageInfo, current, pageSize } }, () => {
          this.getSysList();
        });
      },
      onChange: current => {
        this.setState({ pageInfo: { ...pageInfo, current } }, () => {
          this.getSysList();
        });
      }
    };
    return (
      <div className="sysWrapper">
        <WeaTop
          title={<span>系统配置</span>}
          icon={<i className="icon-coms-Flow-setting"/>}
          iconBgcolor="#F14A2D"
          buttons={btns}
        />
        <WeaTable
          loading={loading.query}
          rowKey="id"
          columns={columns} dataSource={dataSource} pagination={pagination}
          scroll={{ y: `calc(100vh - 162px)` }}
        />
        {/*  新增编辑系统配置项*/}
        <WeaDialog
          {...modalProps}
          initLoadCss
          className="sysModalWrapper"
          buttons={[
            <Button type="ghost" onClick={() => this.setState({
              modalProps: {
                ...modalProps,
                visible: false,
                title: "新增配置项",
                formId: ""
              }
            })}>取消</Button>,
            <Button type="primary" onClick={this.handleSubmit} loading={loading.add || loading.update}>确定</Button>
          ]}
          onCancel={() => this.setState({ modalProps: { ...modalProps, visible: false, title: "新增配置项", formId: "" } })}
        >
          {
            modalProps.visible &&
            <SysForm form={form} condition={sysConditions}/>
          }
        </WeaDialog>
      </div>
    );
  }
}
