import React, { useCallback, useEffect, useState } from "react";
import { Modal, Skeleton, Select, Form, message } from "antd";
import * as API from '../../api';

interface Props{
    visible:boolean;
    row?:API.Item;
    contractTypesList:any[],
    roleList:any[],
    onRefresh: () => void;
    onCancel?: () => void;
}

function AddModel({visible, row, contractTypesList, roleList, onCancel, onRefresh}:Props) {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState<boolean>(false);
    const {id, roles, typeName } = row || {};
    useEffect(() => {
        if (id) {
            form.setFieldsValue({
                contractType: contractTypesList.filter((item:API.TypesItem) => item.name === typeName).map((i:any) => ({label: i.name, value: i.id}))[0],
                roleCode: roles?.length && roles.map((i:any) => ({label: i.roleName, value: i.roleCode})),
            });
        }
    }, [row]);
    
    /**
     * @description: 表单提交
     * @param {any} feildValue
     * @return {*}
     */
    const handleSave = (feildValue: any) => {
        setLoading(true);
        const { roleCode, contractType } = feildValue;
        const _roleCode = roleCode.length && roleCode.map((item:any) => ({roleCode: item.value, roleName: item.label }));
        const params = {roles: _roleCode, typeId: contractType.value, typeName: contractType.label };
        API.addContractAuth({ ...params, contractAuthId: id })
        .then(res => {
            message.success("操作成功"); 
            _onCancel();
            setLoading(false);
            onRefresh();
        })
        .catch(err => {
            message.error(err?.message);
            setLoading(false);
        });
    };
    /**
     * @description: 关闭弹框
     * @param {*}
     * @return {*}
     */
    const _onCancel = () => {
        onCancel && onCancel();
        form.resetFields();
    };
    
    return (
      <Modal
        title={`${id ? '编辑':'新增'}合同授权`}
        visible={visible}
        confirmLoading={loading}
        onCancel={_onCancel}
        onOk={form.submit}
        cancelButtonProps={{ hidden: true }}
        width="50%"
        bodyStyle={{minHeight: 300}}
      >
        <Skeleton
          loading={false}
        >
          <Form form={form} onFinish={handleSave} wrapperCol={{ span: 18 }} labelCol={{ span: 4 }}>
            <Form.Item
              label="合同类型"
              name="contractType"
              rules={[{ required: true, message: '请选择合同类型' }]}
            >
              <Select
                placeholder="请选择合同类型"
                showSearch
                allowClear
                optionFilterProp="children"
                labelInValue
                onSelect={(it:any) => {
                    const item = contractTypesList.filter((i:any) => it.value === i.id);
                }}
                filterOption={(input, option: any) => option?.children.indexOf(input) >= 0}
              >
                {
                  contractTypesList && contractTypesList.map((item:any) => (
                    <Select.Option value={item.id} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))
                }
              </Select>
            </Form.Item>
            <Form.Item
              label="授权角色"
              name="roleCode"
              rules={[{ required: true, message: '请选择授权角色' }]}
            >
              <Select
                placeholder="请选择授权角色(支持多选）"
                mode="multiple"
                showSearch
                allowClear
                showArrow
                optionFilterProp="children"
                labelInValue
                onSelect={(it:any) => {
                    const item = roleList.filter((i:any) => it.value === i.roleCode);
                }}
                filterOption={(input, option: any) => option?.children.indexOf(input) >= 0}
              >
                {
                  roleList && roleList.map((item:any) => (
                    <Select.Option value={item.roleCode} key={item.id}>
                      {item.roleName}
                    </Select.Option>
                  ))
                }
              </Select>
            </Form.Item>
          </Form>
        </Skeleton>
      </Modal>
    );
}

export default AddModel;