import React from "react";
import { inject, observer } from "mobx-react";
import { Button, Col, Dropdown, Menu, message, Modal, Row, Switch } from "antd";
import { WeaFormItem, WeaInputSearch, WeaLocaleProvider, WeaSearchGroup, WeaTable, WeaTop } from "ecCom";
import { renderNoright } from "../../util";
import EditModal from "./editModal";
import TipLabel from "../../components/TipLabel";
import { decentralizationConditions, editConditions } from "./editConditions";
import LogDialog from "../../components/logViewModal";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

@inject("taxAgentStore")
@observer
export default class TaxAgent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      editModalProps: {
        title: "新增个税扣缴义务人",
        visible: false,
        current: 0,
        btnType: "save", //save: 添加， edit: 编辑，  prev: '上一步'
        editId: "",
        editType: "save"
      },
      editModalLoading: {
        saveloading: false
      },
      devolutionStatus: 0,
      conditions: editConditions,
      decentralizationConditions: decentralizationConditions,
      permission: {},
      syncLoading: false,
      logDialogVisible: false,
      filterConditions: "[]"
    };
  }

  componentWillMount() {
    const { taxAgentStore } = this.props;
    const { doInit } = taxAgentStore;
    doInit();
    this.getPermission();
    // window.setLayoutWindow=window;
  }

  getPermission = () => {
    const { getPermission } = this.props.taxAgentStore;
    getPermission().then(({ status, data }) => {
      if (status) {
        this.setState({ permission: data }, () => {
          this.getTaxAgentBaseForm();
        });
      }
    });
  };

  getTaxAgentBaseForm = () => {
    const { taxAgentStore } = this.props;
    const { getTaxAgentBaseForm } = taxAgentStore;
    getTaxAgentBaseForm().then(({ status, data }) => {
      if (status && !_.isEmpty(data)) {
        const { devolutionStatus } = data;
        this.setState({ devolutionStatus });
      }
    });
  };

  taxAgentBaseSave = devolutionStatus => {
    Modal.confirm({
      title: "信息确认",
      content: `确认${!devolutionStatus ? "停用" : "启用"}分权?`,
      onOk: () => {
        const paylaod = { devolutionStatus };
        const { taxAgentStore } = this.props;
        const { taxAgentBaseSave, doInit, pageObj } = taxAgentStore;
        taxAgentBaseSave(paylaod).then(({ status, errormsg }) => {
          if (status) {
            message.success(`${!devolutionStatus ? "停用" : "启用"}分权成功`);
            this.getTaxAgentBaseForm();
            doInit({ current: pageObj.current, pageSize: pageObj.pageSize });
          } else {
            message.error(errormsg || `${!devolutionStatus ? "停用" : "启用"}分权失败`);
          }
        });
      },
      onCancel() {
      }
    });
  };

  getTaxAgentForm = (id, current) => {
    const { conditions, devolutionStatus, decentralizationConditions } = this.state;
    const { taxAgentStore } = this.props;
    const { getTaxAgentForm, getCondition, getFormDecentralizationCondition } = taxAgentStore;
    getTaxAgentForm({ id }).then(({ status, data }) => {
      if (status && !_.isEmpty(data)) {
        const [conditionItem] = devolutionStatus === 1 ? conditions : decentralizationConditions;
        const conditionMap = _.map(conditionItem.items, it => {
          const key = it.domkey.join("");
          if (it.conditionType === "BROWSER") {
            return {
              ...it,
              browserConditionParam: {
                ...it.browserConditionParam,
                replaceDatas: _.map(data[key], b => ({
                  id: b.id,
                  name: b.content
                }))
              },
              viewAttr: (current == 1 || !this.state.permission.isChief) ? 1 : it.viewAttr
            };
          } else {
            if (data[key]) {
              return {
                ...it,
                value: data[key],
                viewAttr: (current == 1 || !this.state.permission.isChief) ? 1 : it.viewAttr
              };
            }
          }
          return { ...it, viewAttr: (current == 1 || !this.state.permission.isChief) ? 1 : it.viewAttr };
        });
        this.setState(
          {
            conditions: [{ defaultshow: true, items: conditionMap }],
            decentralizationConditions: [{ defaultshow: true, items: conditionMap }]
          },
          () => {
            devolutionStatus === 1 ? getCondition(this.state.conditions) : getFormDecentralizationCondition(this.state.decentralizationConditions);
          }
        );
      }
    });
  };

  showEditModal = (editId, current) => {
    this.setState(
      {
        editModalProps: {
          ...this.state.editModalProps,
          visible: true,
          title: editId ? "编辑个税扣缴义务人" : "新增个税扣缴义务人",
          btnType: editId ? "edit" : "save",
          editId: editId,
          editType: current ? "set" : editId && !current ? "edit" : "save",
          current: current ? current : 0
        }
      },
      () => {
        editId && this.getTaxAgentForm(editId, current);
      }
    );
  };

  closeModal = () => {
    const { devolutionStatus } = this.state;
    const { taxAgentStore } = this.props;
    const { form, formDecentralization, getCondition } = taxAgentStore;
    this.setState(
      {
        editModalProps: {
          ...this.state.editModalProps,
          title: "新增个税扣缴义务人",
          current: 0,
          btnType: "save",
          editId: "",
          editType: "save",
          visible: false
        },
        conditions: editConditions,
        decentralizationConditions: decentralizationConditions
      },
      () => {
        devolutionStatus === 1 ? form.resetForm() : formDecentralization.resetForm();
        devolutionStatus === 1 ? getCondition(this.state.conditions) : getCondition(this.state.decentralizationConditions);
      }
    );
  };
  /**
   * name:表单提交
   * return {*}
   */
  handleSubmit = module => {
    const { taxAgentStore } = this.props;
    const { editModalProps } = this.state;
    const { doInit, saveTaxAgent, updateTaxAgent, pageObj } = taxAgentStore;
    const { btnType, editId, editType } = editModalProps;
    if (btnType === "save") {
      // 新增
      this.setState({
        editModalLoading: {
          saveloading: true
        }
      });
      const payload = { ...module };
      saveTaxAgent(payload).then(({ status, errormsg, data }) => {
        this.setState({
          editModalLoading: {
            saveloading: false
          }
        });
        if (status) {
          message.success("新增成功");
          this.setState({
            editModalProps: {
              ...editModalProps,
              editId: data,
              current: 1,
              btnType: "prev"
            }
          });
          doInit({ current: pageObj.current, pageSize: pageObj.pageSize });
        } else {
          message.error(errormsg || "新增失败");
        }
      });
    } else if (btnType === "edit") {
      // 编辑
      this.setState({
        editModalLoading: {
          saveloading: true
        }
      });
      const payload = { ...module, id: editId };
      updateTaxAgent(payload).then(({ status, errormsg }) => {
        this.setState({
          editModalLoading: {
            saveloading: false
          }
        });
        if (status) {
          message.success("更新成功");
          if (editType === "edit") {
            this.closeModal();
          } else {
            this.setState({
              editModalProps: {
                ...editModalProps,
                current: 1,
                btnType: "prev"
              }
            });
          }
          doInit({ current: pageObj.current, pageSize: pageObj.pageSize });
        } else {
          message.error(errormsg || "更新失败");
        }
      });
    }
  };
  /**
   * name: 删除个税扣缴义务人
   * param {*} agentId
   * return {*}
   */
  deleteTaxAgent = agentId => {
    const { taxAgentStore } = this.props;
    const { deleteTaxAgent, pageObj, doInit } = taxAgentStore;
    Modal.confirm({
      title: "信息确认",
      content: `确认要删除吗?`,
      onOk: () => {
        deleteTaxAgent([agentId]).then(({ status, errormsg }) => {
          if (status) {
            message.success("删除成功");
            doInit({ current: pageObj.current, pageSize: pageObj.pageSize });
          } else {
            message.error(errormsg || "删除失败");
          }
        });
      }
    });
  };
  taxAgentRangeSync = () => {
    const { taxAgentStore } = this.props;
    const { taxAgentRangeSync, getTaxAgentList } = taxAgentStore;
    this.setState({ syncLoading: true });
    taxAgentRangeSync({}).then(({ status, data }) => {
      this.setState({ syncLoading: false });
      if (status) {
        message.success(data || "操作成功");
        getTaxAgentList();
      }
    });
  };
  onDropMenuClick = (key, targetid = "") => {
    switch (key) {
      case "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: targetid ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${targetid}\"}]` : "[]"
        });
        break;
      default:
        break;
    }
  };


  render() {
    const { taxAgentStore } = this.props;
    const {
      editModalProps,
      editModalLoading,
      devolutionStatus,
      conditions,
      decentralizationConditions,
      permission,
      syncLoading,
      name,
      logDialogVisible,
      filterConditions
    } = this.state;
    const {
      loading,
      pageObj,
      dataSource,
      columns,
      doInit,
      hasRight,
      getTaxAgentList,
      showOperateBtn
    } = taxAgentStore;

    if (!hasRight && !loading) {
      // 无权限处理
      return renderNoright();
    }

    const btns = [
      <Button type="primary" onClick={this.taxAgentRangeSync} loading={syncLoading}>同步人员范围</Button>,
      <WeaInputSearch
        value={name}
        style={{ width: 250 }}
        placeholder="请输入个税扣缴义务人名称"
        onChange={name => this.setState({ name })}
        onSearch={() => getTaxAgentList({ name, current: 1 })}
      />
    ];
    const renderTipsLabel = () => {
      const tipList = [
        "1、个税扣缴义务人与档案中的个税扣缴义务人匹配，修改个税扣缴义务人名称，薪资档案的个税扣缴义务人数据同步更新；",
        "2、删除个税扣缴义务人需先确认档案里无人员使用该个税扣缴义务人，否则不予删除；",
        "3、只有薪酬总管理员能够操作个税扣缴义务人的增减和开启/关闭分权；",
        "4、总管理员通过后台设置“薪酬管理权限”权限项进行配置；"
      ];
      return <TipLabel tipList={tipList}/>;
    };

    const pagination = {
      total: pageObj.total,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onShowSizeChange(current, pageSize) {
        doInit({ current, pageSize });
      },
      onChange(current) {
        doInit({ current, pageSize: pageObj.pageSize });
      }
    };
    const newColumns = _.map(
      [
        ...columns,
        {
          title: "操作",
          key: "operation",
          render: (text, record) =>
            <div className="operationWapper">
              <a
                href="javaScript:void(0);"
                onClick={() => this.showEditModal(record.id)}>
                编辑
              </a>
              <a
                href="javaScript:void(0);"
                onClick={() => this.deleteTaxAgent(record.id)}>
                删除
              </a>
              <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item>
                      <a href="javascript:void(0)"
                         onClick={() => this.onDropMenuClick("log", record.id)}>{getLabel(545781, "操作日志")}</a>
                    </Menu.Item>
                  </Menu>
                }>
                <a href="javascript:void(0)"><i className="icon-coms-more"/></a>
              </Dropdown>
            </div>
        }
      ],
      item => {
        if (item.dataIndex === "employeeRange") {
          return {
            ...item,
            render: (text, record) => {
              return (
                <div className="employeeRangeWapper">
                  <a
                    href="javaScript:void(0);"
                    onClick={() => this.showEditModal(record.id, 1)}>
                    {text}
                  </a>
                </div>
              );
            }
          };
        } else {
          return { ...item };
        }
      }
    );

    return (
      <div className="taxWithholdingAgentWrapper">
        <WeaTop title="个税扣缴义务人" icon={<i className="icon-coms-fa"/>} iconBgcolor="#F14A2D"
                buttons={showOperateBtn ? btns : btns.slice(1)} showDropIcon onDropMenuClick={this.onDropMenuClick}
                dropMenuDatas={[
                  {
                    key: "log", icon: <i className="iconfont icon-caozuorizhi32"/>,
                    content: getLabel(545781, "操作日志")
                  }
                ]}
        >
          <Row
            gutter={16}
            style={{ overflow: "hidden", width: "100%", marginTop: 8 }}>
            <Col sm={24} md={24} lg={18} xl={18}>
              <div className="mySalaryTableWrapper">
                {permission.isChief &&
                  <WeaSearchGroup title={"基础信息"} showGroup>
                    <WeaFormItem
                      label="启用分权"
                      labelCol={{ span: 4 }}
                      wrapperCol={{ span: 20 }}>
                      <Switch
                        checked={devolutionStatus === 1}
                        onChange={this.taxAgentBaseSave}
                      />
                    </WeaFormItem>
                  </WeaSearchGroup>}
                <WeaSearchGroup
                  title={
                    <div className="titleWrapper">
                      <div className="title">个税扣缴义务人</div>
                      {/* 总管理员开启新增功能 */}
                      {permission.isChief &&
                        <i
                          className="icon-coms-Add-to"
                          title="新增"
                          onClick={() => this.showEditModal()}
                        />}
                    </div>
                  }
                  showGroup>
                  <WeaTable
                    columns={newColumns}
                    dataSource={dataSource}
                    pagination={pagination}
                    loading={loading}
                  />
                </WeaSearchGroup>
              </div>
            </Col>
            <Col sm={24} md={24} lg={6} xl={6}>
              {renderTipsLabel()}
            </Col>
          </Row>
        </WeaTop>
        {/*操作日志*/}
        <LogDialog visible={logDialogVisible} logFunction="taxagent" filterConditions={filterConditions}
                   onCancel={() => this.setState({ logDialogVisible: false })}/>
        {editModalProps.visible &&
          <EditModal
            {...editModalProps}
            {...editModalLoading}
            devolutionStatus={devolutionStatus}
            editConditions={devolutionStatus === 1 ? conditions : decentralizationConditions}
            taxAgentStore={taxAgentStore}
            isChief={permission.isChief}
            onPrev={() =>
              this.setState({
                editModalProps: {
                  ...editModalProps,
                  current: 0,
                  btnType: "edit"
                }
              })}
            onChangeTab={current => {
              this.setState({
                editModalProps: {
                  ...editModalProps,
                  current
                }
              });
            }}
            onClose={this.closeModal}
            onSubmit={this.handleSubmit}
          />}
      </div>
    );
  }
}
