import { useEffect, useState, useContext } from 'react';
import { Form, Input, Button, Tabs, Space, Switch, Breadcrumb, Radio, TreeSelect, message, Modal } from 'antd';
import './index.less';
import DataContext from './data-context';
import SelectedTag from '@common/SelectedTag.js';
import MyDeptStruct from '@common/MyDeptStruct.js';
import { useSelector } from 'react-redux'
import apiObj from '@api/index';
import {filterIds } from '@utils/index';
import backIcon from "@images/back.png";
import DoctorList from "./doctorList"
const { api, xPost } = apiObj;

const { SHOW_PARENT } = TreeSelect;
const { TabPane } = Tabs;
function AddData(props) {
  useEffect(() => {
    getOrgList();
    if (isEdit) {
        setEditData();
    }
  }, []);
  const { back } = props;
  const [form] = Form.useForm();
  const [isChange, setIsChange] = useState(false);
  const [visible, setVisible] = useState(false);

  const [checkedUser, setCheckedUser] = useState([]);   //指定用户选中项
  const [checkedUserIds, setCheckedUserIds] = useState([]);   //指定用户选中项id
  const [checkedDepts, setCheckedDepts] = useState([]);   //指定科室选中项
  const [checkedDeptIds, setCheckedDeptIds] = useState([]);   //指定科室选中的科室项id
  const [checkedHosIds, setCheckedHosIds] = useState([]);   //指定科室选中的医院项id
  const [checkedTreeItems, setCheckedTreeItems] = useState([]);   //指定科室选中的树结构

  const [value, setValue] = useState([]);
  const [tabKey, setTabKey] = useState();       //权限范围选中的tab id
  const [tabIndex, setTabIndex] = useState('0');      //权限范围选中的tab index
  const [showCustom,setShowCustom]=useState(false);     //是否显示自定义内容
    const [treeRloe, setTreeRloe] = useState([]);
  const [tags, setTags] = useState([[]]);
  const [orgList, setOrgList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const { save, formData, operType, val, tag,authChecksArr, originData} = useContext(DataContext);
  const isEdit = operType===3;      //是否为编辑
  const staticInfo = useSelector(state => {
    return state.staticInfo;
  });
  const { dataList } = staticInfo;
  const initialValues = formData
  const validateMessages = {
    required: '${label}不能为空',
  };
  function handleOk() {
    back()
  }
  function handleCancel() {
    setVisible(false)
  }
  const goback = () => {
    if (form.isFieldsTouched()) {
      setVisible(true)
    } else {
      back()
    }
  };
  //编辑数据填充
    function setEditData(){
        const data = (originData[tabIndex]||{}).dataAuthDetail||{};
        const sysObj = form.getFieldValue().softwareVOS[tabIndex]||{};
        const dataType = sysObj.dataType;
        const isCustom = dataType === '7';
        //判断权限范围类型，是否显示自定义内容
        setShowCustom(isCustom);
        if(!isCustom||!data){      //非自定义不处理
            return;
        }
        const depts = data.depts||[];
        const doctors = data.doctors||[];
        const hospitals = data.hospitals||[];
        const hosIds = filterIds(hospitals);
        const deptIds = filterIds(depts);
        setCheckedUser(doctors);
        setCheckedUserIds(filterIds(doctors,['id','name']));
        setCheckedTreeItems(filterIds(hospitals,['hospitalId','hospitalName','id','name'],true));
        setCheckedHosIds(hosIds);
        //setHosArr(hospitals||[]);
        setCheckedDepts([...hospitals,...depts]);
        setCheckedDeptIds(hosIds.concat(deptIds));
    }
  //获取当前用于所属角色
  function getCreateRoles(softwareId) {
    const params = {
      softwareId: softwareId
    }
    xPost(api.getCreateRoles, params).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        let arr = JSON.parse(JSON.stringify(data).replace(/name/g, 'title').replace(/id/g, 'value'))
        setTreeRloe(arr)
      }
    })
  }

  //获取组织列表
  function getOrgList() {
    xPost(api.getUserHospitals).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        const { software } = data;
        setOrgList(software);
          setTabKey(software[0].id)
        getCreateRoles(software[0].id)
        if (isEdit) {
          software.forEach((it, index) => {
            tag.forEach((item, i) => {
              tags[index] = []
              if (i == index) {
                tags[index] = tag[i]
              }
            })
            setTags([...tags])
          })
        } else {
          software.forEach((it, index) => {
            tags[index] = []
            setTags([...tags])
          })
        }
      } else {
        message.warning(res.data.msg || '获取医院列表失败');
      }
    }).catch(() => {
      message.error("接口出错");
    });
  }

  const onChange = (e, i) => {
    let val = value
    const formData = form.getFieldsValue();
    let arr = formData.softwareVOS;
    arr[tabIndex].id = tabKey
    arr[tabIndex].softwareMenuIds = []
    arr[tabIndex].dataAuthDetails = []
    //arr[tabIndex].selectedRowKeys = []
    if (e.target.value !== '7') {
      setShowCustom(false);
      arr[tabIndex].dataAuthDetails = [{
        dataType: e.target.value
      }]
    }else{
        setShowCustom(true);
    }
    //tags[tabIndex] = []
    val[i] = e.target.value
    //selectedRowKeys[tabIndex] = []
    form.setFieldsValue({
      softwareVOS: arr
    });
    //setTags([...tags])
    //setValue([...val])
    //setSelectedRowKeys([...selectedRowKeys])
    setIsChange(true)
  };

  function callback(key) {
    const ikey = key.split('-');
    setTabKey(ikey[0])
    setTabIndex(ikey[1])
    const soft = form.getFieldValue().softwareVOS[ikey[1]];
    if(soft){
        setShowCustom(soft.dataType === '7');
    }else{
        setShowCustom(false);
    }
    getCreateRoles(ikey[0])
  }
  function treeChange(value) {
    const formData = form.getFieldsValue();
    let arr = formData.softwareVOS;
    arr[tabIndex].roles = value
    form.setFieldsValue({
      softwareVOS: arr
    });
    setIsChange(true)
  }
  // 去重
  function unique(arr) {
    let result = {};
    let finalResult = [];
    for (let i = 0; i < arr.length; i++) {
      result[arr[i].detailId] = arr[i];
    }

    for (let item in result) {
      finalResult.push(result[item]);
    }
    return finalResult;
  }
  //医生选中
  function checkDoctEvent(selectedRowKeys) {
    const formData = form.getFieldsValue();
    //const tempAuthData = formData.softwareVOS[tabIndex].dataAuthDetails;
    let arr = [];
    let docIds=[];
    selectedRowKeys.forEach(it => {
      arr.push({
        id: it.split('-')[0],
        dataType: '7',
        detailId: it.split('-')[0],
        detailType: 3,
        name: it.split('-')[1],
      })
      docIds.push(it);
    });
    const docArr = unique(arr);
    formData.softwareVOS[tabIndex].dataAuthDetails = [...docArr,...checkedDepts];
    //formData.softwareVOS[tabIndex].selectedRowKeys = selectedRowKeys;
    form.setFieldsValue({
      softwareVOS: formData.softwareVOS
    });
    //保存需要展示的已选中标签数据
    setCheckedUser(docArr)
    setCheckedUserIds(docIds);
  }
  //树形结构选中事件
    //选中科室
    function handleCheckDept(checks,e){
        setCheckedTreeItems(checks);
        //排序，短的在前长的在后，为去重(组织下全选，只传组织id)做准备
        const posArr = [...e.checkedNodesPositions].sort((a,b)=>{
            return a.pos.length-b.pos.length;
        });
        //console.log('排序后：',posArr);
        const structDepts = structureDeptTag(posArr);
        const {deptIds,hosIds,paramHos,paramDept} = structDepts;
        let deptIdsArr=[...deptIds];
        let deptArr=[...paramDept];
        let hosIdsArr=[...hosIds];
        let hosArr=[...paramHos];console.log('树选中：',hosIdsArr)
        setCheckedDepts(hosArr.concat(deptArr));        //显示的排序可能需要再考虑一下
        setCheckedDeptIds(deptIdsArr);
        setCheckedHosIds(hosIdsArr);
        const tempFormData = form.getFieldsValue();
        tempFormData.softwareVOS[tabIndex].dataAuthDetails=[...checkedUser,...hosArr,...deptArr];
        form.setFieldsValue(tempFormData);
    }
    //格式化选中科室数据
    function structureDeptTag(pos){   //全选传医院id，非全选传科室id
        let tempPos=[],hosIds=[],hosArr=[],len=0,deptIds=[],deptArr=[],temp=[],tempKey='';//作为已选中标签显示的数据
        let paramHos=[],paramDept=[];   //作为新增接口参数的数据
        let it=null,checks=[];
        for(let i=0;i<pos.length;i++){
            it=pos[i];
            tempKey=it.node.key;
            if(it.pos==='0-0'){     //全选了平台，终止遍历
                temp = tempKey.split("-");
                //hosArr.push({key:tempKey});
                paramHos.push({id:temp[0],detailId:temp[0],detailType:1,name:temp[1],dataType:'7',key:tempKey});
                hosIds.push(temp[0]);
                setCheckedTreeItems([tempKey]);
                return {hosIds:hosIds,deptIds:deptIds,deptObj:deptArr};
            }
            //如果当前节点的pos包含了tempPos里的某个数据，说明该节点的父节点已被选中并记录，自身则不需要记录
            if(!(tempPos.includes(it.pos.substr(0,5))||tempPos.includes(it.pos.substr(0,7)))){
                tempPos.push(it.pos);       //记录需要展示的节点pos,作为去重的依据
                temp = tempKey.split("-");
                len=temp.length;
                //记录选中的节点id,从已选中标签中删除时控制树形结构选中状态用
                checks.push(tempKey);
                setCheckedTreeItems(checks);
                //医院id存入sendHospitals，科室id存入sendDepts
                if(len===2){
                    //hosArr.push({key:tempKey});
                    paramHos.push({id:temp[0],detailId:temp[0],name:temp[1],detailType:1,dataType:'7',key:tempKey});
                    hosIds.push(temp[0]);
                }else{
                    //deptArr.push({key:tempKey});
                    paramDept.push({id:temp[2],detailId:temp[2],detailType:2,name:temp[1]+"-"+temp[3],dataType:'7',key:tempKey});
                    deptIds.push(temp[2]);
                }

            }
        }
        return {hosIds:hosIds,deptIds:deptIds,paramDept,paramHos};
    }
    //删除已选用户/科室
    function handleTagDel(idx,type){ //type=1可看意思，type=2可看科室
        if(idx===undefined){    //无入参，清空所有
            //情况树状结构选中状态
            setCheckedTreeItems([]);
            //清空用户
            setCheckedUser([]);
            setCheckedUserIds([]);
            //清空科室
            setCheckedDepts([]);
            setCheckedDeptIds([]);
            setCheckedHosIds([]);
            const tempFormData = form.getFieldsValue();
            tempFormData.softwareVOS[tabIndex].dataAuthDetails=[];
            form.setFieldsValue(tempFormData);
            return;
        }
        //const idx=checkedUserIds.findIndex((it)=>it===id);
        const tempFormData = form.getFieldsValue();
        if(type===1){
            let checkedIdsArr=[...checkedUserIds];
            let checkedUserArr=[...checkedUser];
            checkedIdsArr.splice(idx,1);
            checkedUserArr.splice(idx,1);
            setCheckedUser(checkedUserArr);
            setCheckedUserIds(checkedIdsArr);
            tempFormData.softwareVOS[tabIndex].dataAuthDetails=[...checkedUserArr,...checkedDepts];
            form.setFieldsValue(tempFormData);
        }else if(type===2){
            //删除树结构中对应的选中状态
            const ikey = checkedDepts[idx].key;
            const tempItems = [...checkedTreeItems];
            const index = tempItems.findIndex((it)=>it===ikey);
            tempItems.splice(index,1);
            setCheckedTreeItems(tempItems);
            //console.log(ikey,index,checkedDepts,checkedTreeItems,tempItems)
            //删除对应的显示数据及传参数据
            let checkedDeptsArr=[...checkedDepts];
            let checkedHosIdsArr=[...checkedHosIds];
            let checkedDeptIdsArr=[...checkedDeptIds];
            checkedDeptsArr.splice(idx,1);
            checkedHosIdsArr.splice(idx,1);
            checkedDeptIdsArr.splice(idx-checkedHosIdsArr.length,1);
            setCheckedDepts(checkedDeptsArr);            //选中的科室和医院合并过的
            setCheckedHosIds(checkedHosIdsArr);
            setCheckedDeptIds(checkedDeptIdsArr);
            tempFormData.softwareVOS[tabIndex].dataAuthDetails=[...checkedUser,...checkedDeptsArr];
            form.setFieldsValue(tempFormData);
        }
    }

  const onFinish = () => {
      console.log(form.getFieldsValue());
    save(form.getFieldsValue())
  };
  function swichChange(val) {
    form.setFieldsValue({ status: val ? 1 : 0 })
  }
  return (
    <>
      <Breadcrumb separator="">
        <Breadcrumb.Item><img className='back-icon' src={backIcon} onClick={goback} alt="返回上一页" /></Breadcrumb.Item>
        <Breadcrumb.Item>数据权限</Breadcrumb.Item>
        <Breadcrumb.Separator />
        <Breadcrumb.Item>{isEdit ? '修改' : '新增'}数据权限</Breadcrumb.Item>
      </Breadcrumb>
      <div className='form-center'>
        <Form labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} form={form} name="nest-messages" onFinish={onFinish} initialValues={initialValues} validateMessages={validateMessages}>
          <Form.Item name="name" label="数据权限名称" rules={[{ required: true }]}>
            <Input placeholder="请填写数据权限名称" style={{ width: 300 }} autoComplete='off'/>
          </Form.Item>
          <Form.Item label="权限范围" rules={[{ required: true }]} >
            <Tabs type="card" onChange={callback}>
              {
                orgList.map((it, i) => {
                  return (
                    <TabPane tab={it.name} key={it.id + "-" + i} forceRender={isEdit && form.getFieldValue().softwareVOS[i] ? true : false}>
                      <Form.Item
                        key={i}
                        name={['softwareVOS', i, 'dataType']} noStyle>
                        <Radio.Group onChange={e => { onChange(e, i) }} className="radio">
                          <Space direction="vertical">
                            {dataList.map((Item) => {
                              return (
                                <Radio key={i} value={Item.name}>{Item.val}</Radio>
                              )
                            })
                            }
                          </Space>
                        </Radio.Group>
                      </Form.Item>
                      <Form.Item key={i + "a"} hidden={true} name={['softwareVOS', i, 'id']} noStyle>
                        <Input />
                      </Form.Item>
                      <Form.Item key={i + "b"} hidden={true} name={['softwareVOS', i, 'dataAuthDetails']} noStyle>
                        <Input />
                      </Form.Item>
                      <Form.Item key={i + "e"} hidden={true} name={['softwareVOS', i, 'roles']} noStyle>
                        <Input />
                      </Form.Item>
                      <Form.Item key={i + "c"} style={{ display: showCustom && it.id == tabKey ? 'block' : 'none' }}>
                          <SelectedTag userData={checkedUser} deptData={checkedDepts} delTag={handleTagDel}></SelectedTag>
                      </Form.Item>
                      <Form.Item key={i + "d"} style={{ display: showCustom && it.id == tabKey ? 'block' : 'none' }}>
                        <Tabs defaultActiveKey="0" className='tab-content'>
                          <TabPane tab="可看医生" key="0" forceRender={isEdit && form.getFieldValue().softwareVOS[i] ? true : false}>
                            <Form.Item
                              name={['softwareVOS', i, 'selectedRowKeys']}
                            >
                              <DoctorList checkeds={checkedUserIds} checkDoct={(selectedRowKeys) => checkDoctEvent(selectedRowKeys)} />
                            </Form.Item>
                          </TabPane>
                          <TabPane tab="可看科室" key="1" forceRender={isEdit && form.getFieldValue().softwareVOS[i] ? true : false}>
                            <Form.Item>
                              <MyDeptStruct checkeds={checkedTreeItems} checkEv={handleCheckDept} />
                            </Form.Item>
                          </TabPane>
                        </Tabs>
                      </Form.Item>
                    </TabPane>
                  )
                })
              }
            </Tabs>
          </Form.Item>
          <Form.Item label="所属角色" style={{marginLeft: '123px'}} required>
            {
              orgList.map((it, i) => {
                return (
                  <Form.Item
                    key={i}
                    style={{ display: i == tabIndex ? 'block' : 'none' }}
                  >
                    {tabIndex == i ?
                      <Form.Item key={i + "b"}
                        name={['softwareVOS', i, 'roles']}
                        rules={[
                          {
                            required: true,
                            message: '请选择所属角色',
                          },
                        ]}>
                        <TreeSelect
                          style={{ width: 300 }}
                          showSearch={false}
                          treeData={treeRloe}
                          onChange={treeChange}
                          maxTagCount={1}
                          treeCheckable
                          showCheckedStrategy={SHOW_PARENT}
                          placeholder="请选择角色"
                        />
                      </Form.Item>
                      : null}

                  </Form.Item>
                )
              })
            }
          </Form.Item>
          <Form.Item
            name="status"
            valuePropName="checked"
            label="当前状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Switch onChange={swichChange} />
          </Form.Item>
          <Form.Item wrapperCol={{ span: 6, offset: 20 }}>
            <Button className='but' onClick={goback}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
        <Modal
          title="提示"
          okText='确定'
          cancelText='取消'
          width={400}
          visible={visible}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <p>您还有内容未保存，确定要退出？</p>
        </Modal>
      </div>
    </>
  )
}

export default AddData;