/*
  *  角色详情设置弹窗
  *
  * @Author:    黎永顺
  * @Date:      2024/8/5
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import {
  WeaBrowser,
  WeaDialog,
  WeaFormItem,
  WeaInputNumber,
  WeaLocaleProvider,
  WeaScope,
  WeaSelect,
  WeaTab,
  WeaTable,
  WeaTextarea,
  WeaTools
} from "ecCom";
import { commonEnumList } from "../../../../apis/archive";
import EditRoleDialog from "./editRoleDialog";
import DetailDialog from "./detailDialog";
import AuthTree from "./authTree";
import * as API from "../../../../apis/taxAgent";
import { Button, Col, message, Modal, Row } from "antd";
import "../index.less";
import CustomBrowser from "../../../../components/CustomBrowser";
import { roleConditions } from "../conditions";
import { getSearchs } from "../../../../util";

const getLabel = WeaLocaleProvider.getLabel;
const getKey = WeaTools.getKey;
const APIFOX = {
  "auth.MemberTargetTypeEnum": API.authMemberList,
  "save.auth.MemberTargetTypeEnum": API.saveAuthMember,
  "delete.auth.MemberTargetTypeEnum": API.deleteAuthMember,
  "sync.auth.MemberTargetTypeEnum": API.syncAuthMember,
  "auth.DataTargetTypeEnum": API.authDataList,
  "save.auth.DataTargetTypeEnum": API.saveAuthData,
  "delete.auth.DataTargetTypeEnum": API.deleteAuthData,
  "sync.auth.DataTargetTypeEnum": API.syncAuthData
};

@inject("taxAgentStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: "baseinfo", name: "", options: [], enumType: "", selectedRowKeys: [],
      replaceDatas: [], loading: { set: false, query: false, async: false, delete: false },
      columns: [], dataSource: [], pageInfo: { current: 1, pageSize: 10, total: 0 },
      editOperatorDialog: { visible: false, linkOptions: [], record: {} },
      detailDialog: { visible: false, roleId: "", selectedKey: "" },
      dataTargetSettings: { link: "OR", sortedIndex: null }, conditions: [],
      formData: { taxAgentIds: [], sobIds: [] }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      this.setState({
        name: nextProps.name, selectedKey: nextProps.selectedKey || "baseinfo",
        detailDialog: {
          ...this.state.detailDialog, roleId: nextProps.roleId,
          selectedKey: nextProps.selectedKey || "baseinfo"
        }
      }, () => {
        !["auth.AuthTargetTypeEnum", "baseinfo"].includes(this.state.selectedKey) && this.getEnumList();
        !["auth.AuthTargetTypeEnum", "baseinfo"].includes(this.state.selectedKey) && this.getSettingRoler(nextProps.roleId);
        this.state.selectedKey === "baseinfo" && this.getRole(nextProps.roleId);
        this.state.selectedKey === "auth.DataTargetTypeEnum" && this.getConnectSymbol();
      });
    } else {
      this.setState({
        selectedRowKeys: [], replaceDatas: [], pageInfo: { current: 1, pageSize: 10, total: 0 },
        dataTargetSettings: { link: "OR", sortedIndex: "" }
      });
    }
  }

  getRole = (id) => {
    API.getRole({ id }).then(({ status, data }) => {
      if (status) {
        this.setState({
          conditions: _.map(roleConditions, item => ({
            ...item, items: _.map(item.items, o => {
              if (getKey(o) === "taxAgentIds" || getKey(o) === "sobIds") {
                return {
                  ...o, label: getLabel(o.lanId, o.label),
                  value: _.map(data[getKey(o)], i => String(i.id)).join(","),
                  browserConditionParam: {
                    ...o.browserConditionParam,
                    replaceDatas: _.map(data[getKey(o)], i => ({ id: String(i.id), name: i.name }))
                  }
                };
              }
              return { ...o, label: getLabel(o.lanId, o.label) };
            })
          })),
          formData: {
            taxAgentIds: _.map(data["taxAgentIds"], i => ({ id: String(i.id), name: i.name })),
            sobIds: _.map(data["sobIds"], i => ({ id: String(i.id), name: i.name }))
          }
        }, () => {
          this.props.taxAgentStore.roleForm.initFormFields(this.state.conditions);
          this.props.taxAgentStore.roleForm.updateFields({
            name: { value: data.name },
            description: { value: data.description }
          });
        });
      }
    });
  };
  getEnumList = () => {
    const payload = { enumClass: `com.engine.salary.enums.${this.state.selectedKey}` };
    commonEnumList(payload).then(({ status, data }) => {
      if (status) this.setState({
        options: _.map(data, o => ({ key: o.enum, showname: o.defaultLabel })),
        enumType: _.head(data).enum || ""
      });
      if (!status) this.setState({ options: [], enumType: "" });
    });
  };
  getSettingRoler = (roleId) => {
    const { selectedKey, pageInfo } = this.state;
    this.setState({ loading: { ...this.state.loading, query: true } });
    APIFOX[selectedKey]({ roleId, ...pageInfo }).then(({ status, data }) => {
      this.setState({ loading: { ...this.state.loading, query: false } });
      if (status) {
        const { columns, list: dataSource, pageNum: current, pageSize, total } = data;
        this.setState({
          dataSource, pageInfo: { ...pageInfo, current, pageSize, total },
          columns: [
            ...columns, {
              dataIndex: "opt", title: getLabel(111, "操作"), width: 120,
              render: (__, record) => (<a href="javascript:void(0);"
                                          onClick={() => this.handleEditOperator(record)}>{getLabel(111, "编辑")}</a>)
            }
          ]
        });
      }
    });
  };
  handleEditOperator = (record) => {
    this.setState({ editOperatorDialog: { ...this.state.editOperatorDialog, visible: true, record } });
  };
  getConnectSymbol = async () => {
    const payload = { enumClass: `com.engine.salary.enums.auth.DataLinkEnum` };
    const { data } = await commonEnumList(payload);
    const linkOptions = _.map(data, o => ({ key: o.enum, showname: o.defaultLabel }));
    this.setState({ editOperatorDialog: { ...this.state.editOperatorDialog, linkOptions } });
  };
  addOperatorSettings = () => {
    const { roleId } = this.props;
    const { selectedKey, enumType: targetType, replaceDatas, dataTargetSettings } = this.state;
    if (_.isEmpty(replaceDatas)) {
      Modal.warning({
        title: getLabel(111, "系统提示"),
        content: getLabel(111, "请先选择操作对象的值！")
      });
      return;
    }
    const payload = _.map(replaceDatas, o => ({
      roleId, target: o.id || "", id: o.editId || "",
      targetType: o.targetType || targetType,
      targetName: o.name || "",
      link: o.link || dataTargetSettings.link,
      sortedIndex: o.sortedIndex || dataTargetSettings.sortedIndex
    }));
    this.setState({ loading: { ...this.state.loading, set: true } });
    APIFOX[`save.${selectedKey}`](payload).then(({ status, errormsg }) => {
      this.setState({ loading: { ...this.state.loading, set: false } });
      if (status) {
        message.success(getLabel(111, "操作成功！"));
        this.setState({ replaceDatas: [] }, () => this.getSettingRoler(roleId));
      } else {
        message.error(errormsg);
      }
    });
  };
  deleteOperatorSettings = () => {
    const { roleId } = this.props;
    const { selectedKey, selectedRowKeys } = this.state;
    if (_.isEmpty(selectedRowKeys)) {
      Modal.warning({
        title: getLabel(111, "信息确认"),
        content: getLabel(111, "确定要删除所选批次吗？")
      });
      return;
    }
    this.setState({ loading: { ...this.state.loading, delete: true } });
    APIFOX[`delete.${selectedKey}`](selectedRowKeys).then(({ status, errormsg }) => {
      this.setState({ loading: { ...this.state.loading, delete: false } });
      if (status) {
        message.success(getLabel(111, "操作成功！"));
        this.setState({ selectedRowKeys: [] }, () => this.getSettingRoler(roleId));
      } else {
        message.error(errormsg);
      }
    });
  };
  saveAuthOpt = () => {
    const { roleId } = this.props, { selectedKey } = this.state;
    if (selectedKey === "baseinfo") {
      this.saveBaseInfo();
      return;
    }
    const { state: { checkedKeys } } = this.authTreeRef;
    const payload = {
      roleId, opts: _.reduce(checkedKeys, (pre, cur) => {
        if (cur.indexOf("query") !== -1 || cur.indexOf("admin") !== -1) {
          const [page, opt] = cur.split("-");
          return [...pre, { page, opt }];
        }
        return pre;
      }, [])
    };
    this.setState({ loading: { ...this.state.loading, set: true } });
    API.saveAuthOpt(payload).then(({ status, errormsg }) => {
      this.setState({ loading: { ...this.state.loading, set: false } });
      if (status) {
        message.success(getLabel(111, "操作成功！"));
        this.props.onSearch && this.props.onSearch();
      } else {
        message.error(errormsg);
      }
    });
  };
  saveBaseInfo = () => {
    const { taxAgentStore: { roleForm }, roleId } = this.props;
    const { formData } = this.state;
    roleForm.validateForm().then(f => {
      if (f.isValid) {
        const payload = roleForm.getFormParams();
        this.setState({ loading: { ...this.state.loading, set: true } });
        API.saveAuthRole({ id: roleId, ...payload, ...formData }).then(({ status, errormsg }) => {
          this.setState({ loading: { ...this.state.loading, set: false } });
          if (status) {
            message.success(getLabel(111, "操作成功！"));
            this.props.onSearch && this.props.onSearch();
          } else {
            message.error(errormsg);
          }
        });
      } else {
        f.showErrors();
      }
    });
  };
  syncAuthData = () => {
    const { roleId } = this.props, { selectedKey } = this.state;
    this.setState({ async: true });
    APIFOX[`sync.${selectedKey}`]({ roleId }).then(({ status, errormsg }) => {
      this.setState({ async: false });
      if (status) {
        message.success(getLabel(111, "操作成功！"));
        this.props.onSearch && this.props.onSearch();
      } else {
        message.error(errormsg);
      }
    });
  };
  getOperatorSetting = () => {
    const { roleId, taxAgentStore: { roleForm } } = this.props;
    const { selectedKey, enumType, replaceDatas, conditions } = this.state;
    if (!["auth.AuthTargetTypeEnum", "baseinfo"].includes(selectedKey)) {
      let browserType = {};
      switch (enumType) {
        case "EMP":
          browserType = { ...browserType, type: 17, title: getLabel(82246, "人员选择") };
          break;
        case "DEPARTMENT":
          browserType = { ...browserType, type: 57, title: getLabel(111, "部门选择") };
          break;
        case "JOB":
          browserType = { ...browserType, type: 278, title: getLabel(111, "岗位选择") };
          break;
        case "SUB_COMPANY":
          browserType = { ...browserType, type: 164, title: getLabel(111, "分部选择") };
          break;
        case "ROLE":
          browserType = { ...browserType, type: 65, title: getLabel(111, "角色选择") };
          break;
        case "SQL":
          return (<Row className="tax_role_browser_form_item">
            <WeaTextarea style={{ width: "100%" }} minRows={3}
                         value={_.head(replaceDatas) ? _.head(replaceDatas).name : ""}
                         onChange={v => this.setState({ replaceDatas: [{ id: v, name: v }] })}/>
          </Row>);
        case "LEVEL":
          return (<WeaFormItem label={getLabel(111, "安全级别")} labelCol={{ span: 2 }} wrapperCol={{ span: 5 }}
                               className="tax_role_browser_form_item">
            <WeaScope isMobx value={_.reduce(replaceDatas, (pre, cur) => cur.id.split("-"), [])}
                      onChange={v => this.setState({ replaceDatas: [{ id: v.join("-"), name: v.join("-") }] })}/>
          </WeaFormItem>);
        case "SOB":
          return (<WeaFormItem label={getLabel(111, "薪资账套")} labelCol={{ span: 2 }} wrapperCol={{ span: 5 }}
                               className="tax_role_browser_form_item">
            <CustomBrowser
              fieldConfig={{
                viewAttr: 2,
                browserConditionParam: {
                  completeURL: "/api/bs/hrmsalary/salarysob/listAuth", dataParams: { filterType: "QUERY_DATA" },
                  filterByName: true, tableProps: {}, isSingle: false, searchParamsKey: "name", replaceDatas
                }
              }}
              value={_.map(replaceDatas, o => (o.id))}
              onCustomChange={replaceDatas => this.setState({
                replaceDatas: _.map(_.values(replaceDatas), o => ({ id: o.id, name: o.name }))
              })}
            />
          </WeaFormItem>);
        case "TAX":
          return (<WeaFormItem label={getLabel(111, "扣缴义务人")} labelCol={{ span: 4 }} wrapperCol={{ span: 6 }}
                               className="tax_role_browser_form_item">
            <CustomBrowser
              fieldConfig={{
                viewAttr: 2,
                browserConditionParam: {
                  completeURL: "/api/bs/hrmsalary/taxAgent/listAuth", dataParams: { filterType: "QUERY_DATA" },
                  filterByName: true, tableProps: {}, isSingle: false, searchParamsKey: "name", replaceDatas
                }
              }}
              value={_.map(replaceDatas, o => (o.id))}
              onCustomChange={replaceDatas => this.setState({
                replaceDatas: _.map(_.values(replaceDatas), o => ({ id: o.id, name: o.name }))
              })}
            />
          </WeaFormItem>);
        default:
          return (<Row className="tax_role_browser_form_item"></Row>);
      }
      return (<Row className="tax_role_browser_form_item">
        <WeaBrowser {...browserType} isSingle={false} inputStyle={{ width: 150 }} replaceDatas={replaceDatas}
                    onChange={(__, ___, replaceDatas) => this.setState({ replaceDatas })}/>
      </Row>);
    } else if (selectedKey === "auth.AuthTargetTypeEnum") {
      return (<AuthTree roleId={roleId} ref={dom => this.authTreeRef = dom}/>);
    }
    return getSearchs(roleForm, conditions, 1, false, this.handleFormChange);
  };
  handleFormChange = (val) => {
    const key = _.keys(val)[0];
    if (key === "taxAgentIds" || key === "sobIds") {
      this.setState({ formData: { ...this.state.formData, ...val } });
    }
  };

  render() {
    const { roleId, taxAgentStore, counts } = this.props;
    const {
      selectedKey, name, options, enumType, pageInfo, columns, dataSource, loading, selectedRowKeys, editOperatorDialog,
      dataTargetSettings, detailDialog
    } = this.state;
    const { linkOptions } = editOperatorDialog;
    const tabs = [
      { title: getLabel(111, "基础信息"), viewcondition: "baseinfo", showcount: true, count: "resources" },
      {
        title: getLabel(111, "成员设置"), viewcondition: "auth.MemberTargetTypeEnum", showcount: true, count: "members"
      },
      { title: getLabel(111, "功能权限"), viewcondition: "auth.AuthTargetTypeEnum", showcount: true, count: "opts" },
      { title: getLabel(111, "数据范围"), viewcondition: "auth.DataTargetTypeEnum", showcount: true, count: "datas" }
    ];
    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.getSettingRoler(roleId));
      },
      onChange: current => {
        this.setState({
          pageInfo: { ...pageInfo, current }
        }, () => this.getSettingRoler(roleId));
      }
    };
    const rowSelection = {
      selectedRowKeys, onChange: (selectedRowKeys) => this.setState({ selectedRowKeys })
    };
    const buttons = [
      <Button type="primary" onClick={this.syncAuthData} loading={loading.async}>{getLabel(111, "同步")}</Button>,
      <Button type="primary" loading={loading.set} onClick={this.saveAuthOpt}>{getLabel(111, "保存")}</Button>
    ];
    ["auth.AuthTargetTypeEnum", "baseinfo"].includes(selectedKey) && buttons.shift();
    !["auth.AuthTargetTypeEnum", "baseinfo"].includes(selectedKey) && buttons.pop();
    !["auth.AuthTargetTypeEnum", "baseinfo"].includes(selectedKey) && buttons.unshift(
      <Button type="primary" onClick={() => this.setState({
        detailDialog: { ...detailDialog, visible: true }
      })}>{selectedKey === "auth.MemberTargetTypeEnum" ? getLabel(111, "成员明细") : getLabel(111, "数据明细")}</Button>
    );
    return (
      <WeaDialog
        {...this.props} hasScroll className="tax_role_set_dialog" initLoadCss
        title={`${getLabel(111, "编辑业务线")}-(${name})`}
        buttons={buttons} style={{
        width: 960, height: 606.6, minHeight: 200, minWidth: 380,
        maxHeight: "90%", maxWidth: "90%", overflow: "hidden", transform: "translate(0px, 0px)"
      }}
      >
        <div className="tax_role_set_container">
          <Row>
            <div className="tax_role_form_item">
              <WeaTab datas={tabs} keyParam="viewcondition" selectedKey={selectedKey} countParam="count" counts={counts}
                      onChange={v => this.setState({
                        selectedKey: v, replaceDatas: [], selectedRowKeys: [],
                        detailDialog: { ...detailDialog, selectedKey: v }
                      }, () => {
                        taxAgentStore.roleForm.resetForm();
                        const { selectedKey } = this.state;
                        !["auth.AuthTargetTypeEnum", "baseinfo"].includes(selectedKey) && this.getEnumList();
                        !["auth.AuthTargetTypeEnum", "baseinfo"].includes(selectedKey) && this.getSettingRoler(roleId);
                        selectedKey === "auth.DataTargetTypeEnum" && this.getConnectSymbol();
                        selectedKey === "baseinfo" && this.getRole(roleId);
                      })}/>
              {
                !["auth.AuthTargetTypeEnum", "baseinfo"].includes(selectedKey) &&
                <WeaSelect options={options} detailtype={3} value={enumType}
                           onChange={v => this.setState({ enumType: v, replaceDatas: [] })}/>
              }
              {this.getOperatorSetting()}
              {
                !["auth.AuthTargetTypeEnum", "baseinfo"].includes(selectedKey) &&
                <Row className="tax_role_operator_setting">
                  {
                    this.state.selectedKey === "auth.DataTargetTypeEnum" &&
                    <Col span={16}>
                      <Row>
                        <Col span={12}>
                          <WeaFormItem label={getLabel(111, "连接符")} labelCol={{ span: 8 }} wrapperCol={{ span: 14 }}>
                            <WeaSelect value={dataTargetSettings.link} options={linkOptions}
                                       onChange={link => this.setState({
                                         dataTargetSettings: { ...dataTargetSettings, link }
                                       })}/>
                          </WeaFormItem>
                        </Col>
                        <Col span={12}>
                          <WeaFormItem label={getLabel(111, "批次")} labelCol={{ span: 8 }} wrapperCol={{ span: 14 }}>
                            <WeaInputNumber value={dataTargetSettings.sortedIndex}
                                            onChange={sortedIndex => this.setState({
                                              dataTargetSettings: { ...dataTargetSettings, sortedIndex }
                                            })}/>
                          </WeaFormItem>
                        </Col>
                      </Row>
                    </Col>
                  }
                  <Col span={8} offset={this.state.selectedKey === "auth.DataTargetTypeEnum" ? 0 : 16}>
                    <Button type="primary" loading={loading.set}
                            onClick={this.addOperatorSettings}>{getLabel(111, "添加操作者设置")}</Button>
                  </Col>
                </Row>
              }
            </div>
          </Row>
          {/*表格*/}
          {
            !["auth.AuthTargetTypeEnum", "baseinfo"].includes(selectedKey) &&
            <Row className="tax_role_operator_setting_table">
              <Col span={24} className="setting_table_title">
                <div className="wea-f12 text-elli operator">
                  <span>{getLabel(111, "已设操作者")}</span>
                  <Button type="ghost" disabled={_.isEmpty(selectedRowKeys)} loading={loading.delete}
                          onClick={this.deleteOperatorSettings}>{getLabel(111, "批量删除")}</Button>
                </div>
                <WeaTable rowKey="id" columns={columns} dataSource={dataSource} bordered loading={loading.query}
                          pagination={pagination} rowSelection={rowSelection}/>
                {/* 编辑操作者*/}
                <EditRoleDialog {...editOperatorDialog} loading={loading.set}
                                onChange={replaceDatas => this.setState({ replaceDatas }, () => this.addOperatorSettings())}
                                onCancel={callback => this.setState({
                                  editOperatorDialog: { ...editOperatorDialog, visible: false, record: {} }
                                }, () => callback && callback())}/>
                {/*成员、数据明细查看*/}
                <DetailDialog {...detailDialog}
                              onCancel={() => this.setState({ detailDialog: { ...detailDialog, visible: false } })}/>
              </Col>
            </Row>
          }
        </div>
      </WeaDialog>
    );
  }
}

export default Index;
