import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Table, Select, Space, Modal, message, Row, Col } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import '@common/common.less';
import apiObj from '@api/index';
import {filterIds } from '@utils/index';
import DataContext from './data-context';
import AddData from './AddData';
const { post, api, xPost } = apiObj;
const { Option } = Select;

function DataManager() {
  useEffect(() => {
    getDataAuthPage();
  }, []);
  const [userList, setUserList] = useState([]);
  const [currentId, setCurrentId] = useState("");   //编辑数据的id
  const [modalType, setModalType] = useState("");
  const [msvisible, setMsvisible] = useState(false);
  const [operType, setOperType] = useState("");   //操作类型：1新增 3修改
  const [addVisible, setaddVisible] = useState(false);
  const [formData, setFormData] = useState(null);
  const [total, setTotal] = useState(0);
  const [authChecksArr, setAuthChecksArr] = useState({});   //选中数据
  const [originData,setOriginData] = useState({});   //编辑的原始数据
  const [tag, setTag] = useState([[]]);
  const [val, setVal] = useState([]);
  const [size, setSize] = useState(15);
  const [current, setCurrent] = useState(1);
  const [params, setParams] = useState({
    pages: 1,
    current: 1,
    size: 15
  });
  const [form] = Form.useForm();
  const tipText = {
    1: '确定要删除该数据权限？',
    2: '确定要禁用该数据权限?',
  };
  let data = {
    pages: 1,
    current: 1,
    size: size
  }
  const showModal = (flag, id) => {
    setOperType(flag)
    setCurrentId(id)
    //新增
    if (flag == 1) {
        setaddVisible(true)
      //新增时状态默认启用
      setFormData({
        status: '1'
      });
      setVal([])
    }
    //修改
    if (flag == 3) {
      getDataAuthById(id)
    }
  }
  //表格数据
  function getDataAuthPage(param) {
    //const param = filterData;
    post(api.getDataAuthPage, param || params).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        setUserList(data.records);
        setTotal(data.total)
      }
    })
  }
  //禁用启用
  const disableAuth = (id, status) => {
    let params = {
      id: id,
      status: status
    }
    xPost(api.disableAuth, params).then((res) => {
      if (res.data.code === 200) {
        getDataAuthPage();
        setMsvisible(false);
        message.success((status ? '启用' : '禁用') + "成功");
      } else {
        message.warning(res.data.message || '操作失败');
      }
    })
  };
  //删除
  const deleteAuth = (id) => {
    let params = {
      id: id,
    }
    xPost(api.deleteAuth, params).then((res) => {
      if (res.data.code === 200) {
        getDataAuthPage();
        setMsvisible(false);
        message.success("删除成功");
      } else {
        message.warning(res.data.msg || '操作失败');
      }
    })
  };
  //查看
  function getDataAuthById(id) {
    xPost(api.getDataAuthById, { id: id }).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
          structEditData(data);
      }else{
          message.warning(res.data.msg || '详情获取失败');
      }
    })
  }
  //重组成提交需要的数据
    function structEditData(data){
        const {id,name,status,softwares} = data;
        let formObj = {
            id,
            name,
            status,
            softwareVOS:[]
        };
        setOriginData(softwares);
        let tempArr = [],authArr=[],checkedsObj={},arrVal=[];   //权限数据
        softwares.map((software,i)=>{
            const {id,name,roles,dataAuthDetail,dataType} = software;
            const {depts,doctors,hospitals} = dataAuthDetail||{};
            tempArr = [...depts||[],...doctors||[],...hospitals||[]];
            //arrVal =
            checkedsObj[i] = fullfillVals(tempArr);
            authArr[i] = {
                id,name,dataType:(dataType||'')+''||'7',roles:filterIds(roles||[]),dataAuthDetails:+dataType===7?arrVal:null
            };
        });
        formObj.softwareVOS = authArr;
        setAuthChecksArr(checkedsObj);
        setFormData(formObj)    //表单数据
        setaddVisible(true);
    }
  function fullfillVals(data){
    if(!data) return null;
    return data.map((it)=>{
      return Object.assign(it,{dataType:'7',detailId:it.id});
    })
  }
  //保存
  function addData(formData) {
    let url = api.addAuth;
    delete formData.roles
    const arr = formData.softwareVOS.filter((it) => {
      if (Object.keys(it).length && it.id ) {
        return it;
      }
    });
    formData.softwareVOS = arr;
    let param = {
      addDataAuthVO: formData,
    }
    if (operType == 3) {
      url = api.updateAuth
      param = {
        updateDataAuthVO: {
          ...formData,
          id: currentId
        },
      }
    }
    post(url, param).then((res) => {
      if (res.data.code === 200) {
        getDataAuthPage();
        setaddVisible(false)
        setFormData(null)
        message.success("修改成功");
      } else {
        message.warning(res.data.msg || '操作失败');
      }
    }).catch(() => {
      message.error("接口出错");
    });
  }
  const onFinish = (value) => {
    const param = {
      ...value,
      ...params
    }
    setCurrent(1)
    setParams(param)
    getDataAuthPage(param);
  };
  const onReset = () => {
    setCurrent(1)
    setParams(data)
    form.resetFields();
    getDataAuthPage(data);
  };
  const messageBox = (type, id) => {
    setMsvisible(true)
    setCurrentId(id)
    setModalType(type)
  };
  const columns = [
    { title: '数据权限名称', dataIndex: 'name', key: 'index' },
    { title: '所属角色', dataIndex: 'roleName', key: 'index' },
    {
      title: '状态', dataIndex: 'status', key: 'status', render: (text, record) => (
        <Space size="middle">
          {record.status == 1 ?
            <span className="Enable">启用</span>
            :
            <span className="Disable">禁用</span>
          }
        </Space>
      )
    },
    {
      title: '操作', dataIndex: 'key', render: (text, record) => (
        <Space size="middle">
          <a onClick={e => showModal(3, record.id)}>修改</a>
          {record.status === '1' ? (<a className="disable" onClick={() => messageBox(2, record.id)}>禁用</a>) : (<a onClick={() => disableAuth(record.id, 1)}>启用</a>)}
          <a className="delete" onClick={() => messageBox(1, record.id)} >删除</a>
        </Space>
      )
    }
  ]
  function showAddData() {
    setaddVisible(true)
  }

  //提示框确认事件
  function handleOk() {
    if (modalType == 1) {
      deleteAuth(currentId, 0)
    } else if (modalType == 2) {
      disableAuth(currentId, 0)
    }
  }
  //提示框取消
  function handleCancel() {
    setMsvisible(false);
  }
  function goBack() {
    setaddVisible(false)
    setFormData(null)
    getDataAuthPage()
  }
  function onSizeChange(current, pageSize) {
    params.current = current
    params.size = pageSize
    setSize(pageSize)
    setCurrent(current)
    setParams(params)
    getDataAuthPage()
  }
  function changePage(page, pageSize) {
    params.current = page
    params.size = pageSize
    setCurrent(page)
    setParams(params)
    getDataAuthPage()
  }
  if (addVisible && formData) { //新增/修改界面
    return (
      <DataContext.Provider value={{ save: addData, formData,originData, operType,authChecksArr, val, tag }}>
        <AddData back={goBack} />
      </DataContext.Provider>
    )
  }
  return (
    <div className="wrapper">
      <div className="filter-box">
        <Form
          form={form}
          name="normal_login"

          onFinish={onFinish}
          initialValues={{ status: '' }}
        >
          <Row gutter={24}>
            <Col span={5} key={0}>
              <Form.Item label="数据权限名称" name="username">
                <Input placeholder="用户名" autoComplete='off'/>
              </Form.Item>
            </Col>
            <Col span={5} key={1}>
              <Form.Item label="所属角色" name="name">
                <Input placeholder="姓名" autoComplete='off'/>
              </Form.Item>
            </Col>
            <Col span={5} key={2}>
              <Form.Item label="当前状态" name="status">
                <Select
                  placeholder="Select a person"
                >
                  <Option value="">全部</Option>
                  <Option value="1">启用</Option>
                  <Option value="0" >禁用</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6} key={3}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button onClick={onReset}>
                  重置
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
      <div className="table">
        <div className="table-header">
          <h2 className="table-title">数据权限</h2>
          <Button type="primary" icon={<PlusOutlined />} onClick={e => showModal(1)}>新增数据权限</Button>
        </div>

        <Table
          columns={columns}
          dataSource={userList}
          scroll={{ y: 'calc(100vh - 360px)'}}
          rowKey={record => record.id + record.roleName}
          pagination={{
            current: current,
            pageSize: size,
            size: 'small',
            showSizeChanger: true,
            pageSizeOptions: ['15', '30', '60', '120'],
            showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条数据`,
            onShowSizeChange: (current, pageSize) => onSizeChange(current, pageSize), // 改变每页数量时更新显示
            onChange: (page, pageSize) => changePage(page, pageSize),//点击页码事件
            total: total
          }} />
      </div>
      <Modal
        title="提示"
        okText='确定'
        cancelText='取消'
        width={400}
        visible={msvisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>{tipText[modalType]}</p>
      </Modal>
    </div >
  )
}

export default DataManager;