import React, { useCallback, useState } from "react";
import { Button, Card, ConfigProvider, Divider, Input, message, Popconfirm, Select, Table } from "antd";
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import zhCN from "antd/lib/locale-provider/zh_CN";
import usePagination from "@/hooks/usePagination";
import useInitial from "@/hooks/useInitail";
import { PlusOutlined } from "@ant-design/icons";
import AddModel from './components/AddModel';
import RolesModel from './components/RolesModel';
import Filter from './components/Filter';
import * as API from './api';
import _ from "lodash";
import moment from 'moment';
import st from "./style.less";

const { Column } = Table;
function AuthorizationSetting() {
    const [visible, setVisible] = useState<boolean>(false);
    const [searchValue, setSearchValue] = useState<API.Item>({});
    const [rolesVisible, setRolesVisible] = useState<boolean>(false);
    const [row, setRow] = useState<API.Item>();
    const [roles, setRoles] = useState<API.Roles[]>();
    const {data: roleList} = useInitial<CommonApi.RoleCodeVO[], any>(API.getAllRoleCodeApi, [], {});
    const {
        list: authList,
        paginationConfig,
        loading,
        innerParams,
        setParams,
    } = usePagination<API.Item>(API.getContractAuthPage, {current: 1, pageSize: 10});
    const {
        list: contractTypesList,
    } = usePagination<API.TypesItem>(API.getContractTypes, {current: 1, pageSize: 999});
    /**
     * @description: 删除
     * @param {*}
     * @return {*}
     * 
     */
    const _delete = (row:API.Item) => {
      const {id} =row;
      API.delContractAuth({contractAuthId: id})
      .then((res) => {
          message.success("操作成功");
          setParams({ ...innerParams }, true);
      })
      .catch((e) => {
          message.error(e.message);
      });
    };

    /**
     * @description: 编辑
     * @param {API} row
     * @return {*}
     */
    const edit = async (row:API.Item) => {
      await setRow(row);
      setVisible(true);
    };

    /**
     * @description: 禁用启用
     * @param {API} row
     * @return {*}
     */
    const handleDisable = (row:API.Item) => {
        const { id, enabled } = row;
        API.disableContractAuth({contractAuthId: id, enabled: !enabled})
        .then((res) => {
            message.success("操作成功");
            setParams({ ...innerParams }, true);
        })
        .catch((err) => {
          message.error(err.message);
        });
    };

    const showRoles = async (row:API.Item) => {
        const {roles} = row;
        try {
            await setRoles(roles);
        } finally {
            setRolesVisible(true);
        }
    };

    return (
      <PageHeaderWrapper title="合同授权">
        <ConfigProvider locale={zhCN}>
          <Card className={st.page}>
            <div className={st.header}>
              <Filter
                contractTypesList={contractTypesList}
                setParams={setParams}
                innerParams={innerParams}
              />
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                    setVisible(true);
                }}
              >
                新增
              </Button>
            </div>
            <Table
              size="middle"
              loading={loading}
              dataSource={authList}
              pagination={{ ...paginationConfig }}
              scroll={{ y: 800 }}
              rowKey={(item: API.Item) => `${item.id}`}
              onChange={(_pagination) => setParams({ ..._pagination }, true)}
            >       
              <Column title="合同类型" width={200} dataIndex="typeName" render={(t) => t || "-"} /> 
              <Column
                title="授权角色"
                width={200}
                dataIndex="id"
                render={(text, row:API.Item) => (
                  <Button
                    type="link"
                    onClick={() => showRoles(row)}
                  >
                    查看
                  </Button>     
                )}
              />  
              <Column title="状态" width={200} dataIndex="enabled" render={(t) => (t?'启用':'禁用')} />
              {/* <Column title="创建时间" width={200} dataIndex="createTime" render={(t) => (t ? moment(t).format('YYYY-MM-DD HH:mm') : "-")} /> 
              <Column title="更新时间" width={200} dataIndex="updateTime" render={(t) => (t ? moment(t).format('YYYY-MM-DD HH:mm') : "-")} />  */}
              <Column 
                title="操作"
                width={100} 
                dataIndex="unit"
                render={(text, row:API.Item) => (
                  <span>
                    <Popconfirm title={`是否${row.enabled ? "禁用?":"启用?"}`} onConfirm={() => handleDisable(row)} okText="确定" cancelText="取消">
                      <a
                        onClick={(e) => {
                            e.preventDefault();
                        }}
                        style={{ color: "#FAAD14" }}
                      >
                        {`${row.enabled ? '禁用' :'启用'}`}
                      </a>
                    </Popconfirm>
                    <Divider type="vertical" />
                    <Popconfirm title="是否编辑?" onConfirm={() => edit(row)} okText="确定" cancelText="取消">
                      <a
                        onClick={(e) => {
                            e.preventDefault();
                        }}
                        style={{ color: "#FAAD14" }}
                      >
                        编辑
                      </a>
                    </Popconfirm>
                    <Divider type="vertical" />
                    <Popconfirm title="是否删除?" onConfirm={() => _delete(row)} okText="确定" cancelText="取消">
                      <a
                        onClick={(e) => {
                            e.preventDefault();
                        }}
                        style={{ color: "red" }}
                      >
                        删除
                      </a>
                    </Popconfirm>
                  </span>
                  
                )}
              /> 
            </Table>
            <AddModel 
              visible={visible}
              contractTypesList={contractTypesList}
              roleList={roleList}
              row={row}
              onCancel={() => {
                setVisible(false);
                setRow(undefined);
              }}
              onRefresh={() => setParams({ ...innerParams }, true)}
            />
            <RolesModel
              visible={rolesVisible}
              roles={roles}
              onCancel={() => {
                setRolesVisible(false);
                setRoles(undefined);
              }}
              onRefresh={() => setParams({ ...innerParams }, true)}
            />
          </Card>
        </ConfigProvider>
      </PageHeaderWrapper>
    );
}
export default AuthorizationSetting;
