/*
 * Author: 黎永顺
 * name: 社保福利方案重构-列表
 * Description:
 * Date: 2024/2/2
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaCheckbox, WeaLoadingGlobal, WeaLocaleProvider, WeaTable } from "ecCom";
import { Dropdown, Menu, message, Modal } from "antd";
import TipLabel from "../../../../../components/TipLabel";
import WelfarePlanCopyDialog from "../welfarePlanCopyDialog";
import WelfarePlanCustomDialog from "../welfarePlanCustomDialog";
import WelfarePlanEditSlide from "../welfarePlanEditSlide";
import { tabWelfarePlanList, welfarePlanCopyConditions, welfarePlanCustomTipList } from "../../config";
import * as API from "../../../../../apis/welfareScheme";

const getLabel = WeaLocaleProvider.getLabel;
const APIFOX = {
  SOCIAL_SECURITY: API.getTable,
  ACCUMULATION_FUND: API.getTable,
  OTHER: API.getTable,
  CUSTOM: API.getCustomCategoryList
};

@inject("programmeStore", "taxAgentStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [], columns: [], loading: false,
      pageInfo: { current: 1, pageSize: 10, total: 0 },
      copyDialog: { visible: false, title: "", copyId: "", copyName: "", conditions: [] },
      customDialog: { visible: false, title: "", customId: "" },
      welfarePlanEditSlide: { visible: false, id: "", welfareTypeEnum: "", title: "" }
    };
  }

  componentDidMount() {
    this.getList(this.props);
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if ((nextProps.selectedKey !== this.props.selectedKey) || (nextProps.isQuery !== this.props.isQuery)) {
      this.setState({
        welfarePlanEditSlide: { visible: false, id: "", welfareTypeEnum: "", title: "" },
        pageInfo: { ...this.state.pageInfo, current: 1, pageSize: 10, total: 0 }
      }, () => this.getList(nextProps));
    }
    if ((nextProps.selectedKey !== this.props.selectedKey)) {
      this.setState({
        dataSource: [], columns: [], loading: false,
        pageInfo: { current: 1, pageSize: 10, total: 0 },
        copyDialog: { visible: false, title: "", copyId: "", copyName: "", conditions: [] }
      });
    }
  }

  getList = (props) => {
    const {
      programmeStore: { planSearchForm }, selectedKey: welfareTypeEnum, customQuery,
      taxAgentStore: { showOperateBtn }
    } = props;
    const { pageInfo } = this.state;
    const originPayload = { ...pageInfo, welfareTypeEnum }, customPayload = { welfareTypeEnum: customQuery },
      welfarePayload = { ...planSearchForm.getFormParams() };
    const payload = welfareTypeEnum === "CUSTOM" ? { ...originPayload, ...customPayload } : { ...originPayload, ...welfarePayload };
    this.setState({ loading: true });
    APIFOX[welfareTypeEnum](payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { list: dataSource, columns, pageNum: current, pageSize, total } = data;
        this.setState({
          dataSource, pageInfo: { ...pageInfo, current, pageSize, total },
          columns: _.map(_.filter(columns, o => (o.dataIndex !== "id" && o.dataIndex !== "paymentArea")), g => {
            const { dataIndex } = g;
            let col = { ...g, width: "20%" };
            switch (dataIndex) {
              case "schemeName":
                col = {
                  ...col, width: 250,
                  render: (text, record) => (<a href="javascript:void(0);"
                                                onClick={() => this.handleOpts("edit", record)}>{text}</a>)
                };
                break;
              case "paymentType":
                col = { ...col, width: 100 };
                break;
              case "paymentScope":
                col = welfareTypeEnum !== "CUSTOM" ? { ...col, width: 300 } : {
                  ...col, width: "30%",
                  render: (__, record) => (<span>{record[`${dataIndex}Span`]}</span>)
                };
                break;
              case "remarks":
                col = { ...col, width: 200 };
                break;
              case "welfareType":
                col = {
                  ...col, width: "30%",
                  render: (__, record) => (<span>{record[`${dataIndex}Span`]}</span>)
                };
                break;
              case "isUse":
                col = {
                  ...col, render: (__, record) => (<WeaCheckbox
                    value={record[dataIndex] + ""} display="switch" viewAttr={showOperateBtn ? 2 : 1}
                    onChange={value => this.handleCustomBenefitsSwitch(record, value)}
                  />)
                };
                break;
              default:
                break;
            }
            return col;
          })
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  handleOpts = (key, record = {}) => {
    const { selectedKey, programmeStore: { planCopyForm } } = this.props;
    const { id, schemeName } = record;
    switch (key) {
      case "edit":
        this.setState({
          welfarePlanEditSlide: {
            visible: true, id, welfareTypeEnum: selectedKey,
            title: `${id ? getLabel(501169, "编辑") : getLabel(365, "新建")}${_.find(tabWelfarePlanList, o => o.key === selectedKey).title}${getLabel(111, "方案")}`
          }
        });
        break;
      case "delete":
        Modal.confirm({
          title: getLabel(131329, "信息确认"),
          content: getLabel(111, "确定删除吗？删除后数据不可找回"),
          onOk: () => {
            API.deleteScheme({ welfareTypeEnum: selectedKey, ids: [id] })
              .then(({ status, errormsg }) => {
                if (status) {
                  message.success(getLabel(502230, "删除成功！"));
                  this.getList(this.props);
                } else {
                  message.error(errormsg);
                }
              });
          }
        });
        break;
      case "custom-delete":
        Modal.confirm({
          title: getLabel(131329, "信息确认"),
          content: getLabel(111, "确定删除吗？删除后数据不可找回"),
          onOk: () => {
            WeaLoadingGlobal.start();
            API.deleteCustomCategory({ id }).then(({ status, errormsg }) => {
              WeaLoadingGlobal.destroy();
              if (status) {
                message.success(getLabel(502230, "删除成功！"));
                this.getList(this.props);
              } else {
                message.error(errormsg);
              }
            }).catch(() => WeaLoadingGlobal.destroy());
          }
        });
        break;
      case "custom-edit":
        this.setState({
          customDialog: {
            visible: true, customId: id,
            title: `${id ? getLabel(501169, "编辑") : getLabel(365, "新建")}${getLabel(543151, "自定义福利")}`
          }
        });
        break;
      case "copy":
        this.setState({
          copyDialog: {
            visible: true, copyId: id, copyName: `${schemeName}-${getLabel(77, "复制")}`,
            title: `${getLabel(77, "复制")}-${
              getLabel(_.find(tabWelfarePlanList, o => o.key === selectedKey).lanId, _.find(tabWelfarePlanList, o => o.key === selectedKey).title)
            }`,
            conditions: welfarePlanCopyConditions[selectedKey]
          }
        }, () => {
          const { copyDialog: { conditions, copyName } } = this.state;
          planCopyForm.initFormFields(_.map(conditions, item => ({
            ...item, items: _.map(item.items, o => {
              return { ...o, label: getLabel(o.lanId, o.label) };
            })
          })));
          planCopyForm.updateFields({ [`${selectedKey}_schemeName`]: { value: copyName } });
        });
        break;
      default:
        break;
    }
  };
  handleCustomBenefitsSwitch = ({ id }, isUse) => {
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: isUse === "1" ? getLabel(111, "确定要启用吗？") : getLabel(111, "确定要停用吗？"),
      onOk: () => {
        const payload = { id, isUse };
        API.updateCustomCategoryStatus(payload).then(({ status, errormsg }) => {
          if (status) {
            message.success("操作成功");
            this.getList(this.props);
          } else {
            message.error(errormsg || "操作失败");
            this.setState({
              dataSource: _.map(this.state.dataSource, item => {
                if (item.id === id) {
                  return {
                    ...item, isUse: item.isUse
                  };
                }
                return { ...item };
              })
            });
          }
        });
      },
      onCancel: () => {
        this.setState({
          dataSource: _.map(this.state.dataSource, item => {
            if (item.id === id) {
              return {
                ...item, isUse: item.isUse
              };
            }
            return { ...item };
          })
        });
      }
    });
  };

  render() {
    const { dataSource, columns, pageInfo, loading, copyDialog, customDialog, welfarePlanEditSlide } = this.state;
    const { selectedKey, taxAgentStore: { showOperateBtn } } = this.props;
    const pagination = {
      ...pageInfo,
      showTotal: total => `${getLabel(18609, "共")} ${total} ${getLabel(18256, "条")}`,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onShowSizeChange: (current, pageSize) => {
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize }
        }, () => this.getList(this.props));
      },
      onChange: current => {
        this.setState({
          pageInfo: { ...pageInfo, current }
        }, () => this.getList(this.props));
      }
    };
    const optCols = selectedKey !== "CUSTOM" ? {
      title: getLabel(18610, "操作"),
      dataIndex: "operation", width: 185,
      render: (__, record) => (<div className="planOptBtns">
        <a href="javascript:void(0);"
           onClick={() => this.handleOpts("edit", record)}>{getLabel(501169, "编辑")}</a>
        <a href="javascript:void(0);" onClick={() => this.handleOpts("copy", record)}>{getLabel(77, "复制")}</a>
        <Dropdown
          overlay={
            <Menu>
              <Menu.Item>
                <a href="javascript:void(0)"
                   onClick={() => this.handleOpts("delete", record)}>{getLabel(535052, "删除")}</a>
              </Menu.Item>
              <Menu.Item>
                <a href="javascript:void(0)"
                   onClick={() => this.props.onFilterLog("log", record.id)}>{getLabel(545781, "操作日志")}</a>
              </Menu.Item>
            </Menu>
          }>
          <a href="javascript:void(0)"><i className="icon-coms-more"/></a>
        </Dropdown>
      </div>)
    } : {
      title: getLabel(18610, "操作"),
      dataIndex: "operation", width: 165,
      render: (__, record) => (<div className="planOptBtns">
        <a href="javascript:void(0);"
           onClick={() => this.handleOpts("custom-edit", record)}>{getLabel(501169, "编辑")}</a>
        <a href="javascript:void(0);"
           onClick={() => this.handleOpts("custom-delete", record)}>{getLabel(535052, "删除")}</a>
        <Dropdown
          overlay={
            <Menu>
              <Menu.Item>
                <a href="javascript:void(0);"
                   onClick={() => this.props.onFilterLog("log", record.id)}>{getLabel(545781, "操作日志")}</a>
              </Menu.Item>
            </Menu>
          }>
          <a href="javascript:void(0)"><i className="icon-coms-more"/></a>
        </Dropdown>
      </div>)
    };
    return (
      <div className="welfare-plan-adapt">
        <div className="adapt-left">
          <WeaTable
            rowKey="id" dataSource={dataSource} pagination={pagination} loading={loading}
            scroll={{ y: "calc(100vh - 182px)" }}
            columns={showOperateBtn ? [...columns, optCols] : [...columns, {
              title: getLabel(18610, "操作"),
              dataIndex: "operation", width: 120,
              render: (__, record) => (<a href="javascript:void(0);"
                                          onClick={() => this.handleOpts(selectedKey === "CUSTOM" ? "custom-edit" : "edit", record)}>{getLabel(33564, "查看")}</a>)
            }]}
          />
        </div>
        {
          selectedKey === "CUSTOM" &&
          <div className="adapt-right">
            <TipLabel tipList={_.map(welfarePlanCustomTipList, o => getLabel(o.lanId, o.title))}/>
          </div>
        }
        {/*复制方案*/}
        <WelfarePlanCopyDialog {...copyDialog} selectedKey={selectedKey}
                               onCancel={(isRefrese) => this.setState({
                                 copyDialog: { ...copyDialog, visible: false, conditions: [] }
                               }, () => isRefrese && this.getList(this.props))}
        />
        {/*新建编辑自定义方案*/}
        <WelfarePlanCustomDialog {...customDialog} selectedKey={selectedKey} showOperateBtn={showOperateBtn}
                                 onCancel={(isRefrese) => this.setState({
                                   customDialog: { ...customDialog, visible: false, customId: "" }
                                 }, () => isRefrese && this.getList(this.props))}
        />
        {/*新建编辑方案*/}
        <WelfarePlanEditSlide {...welfarePlanEditSlide} showOperateBtn={showOperateBtn}
                              onClose={(isFresh) => this.setState({
                                welfarePlanEditSlide: { ...welfarePlanEditSlide, visible: false }
                              }, () => isFresh && this.getList(this.props))}
        />
      </div>
    );
  }
}

export default Index;
