/* eslint-disable no-return-assign */
import { Space, Table, Button, Popconfirm, notification, Divider, Checkbox, Spin } from 'antd';
import React, { useState, useEffect, useCallback } from 'react';
import VisibleRoleModal from '@/pages/platformCenter/messageManage/projectManage/components/RolseSelect/VisibleRoleModal';

import { PlusOutlined, UserAddOutlined } from '@ant-design/icons';
import RoleModal from './RoleModal';
import styles from '../SchemeConfig.less';
import {
  deleteConfig,
  setServiceType,
  SetServiceConfig,
  GetMaplayerByTerminalType,
  SetDefaultsSchemeName,
} from '@/services/webConfig/api';
import { RoleGroupList } from '@/services/messagemanage/messagemanage';
import AddModal from './AddModal';
const VectorData = props => {
  const [treeLoading, setTreeLoading] = useState(false); // 弹窗显示
  const [schemename, setSchemename] = useState([]);
  const [record, setRecord] = useState({}); // 选中关联角色的方案名
  const [webCurrent, setWebCurrent] = useState(0); // web列表下标
  const [handCurrent, setHandCurrent] = useState(0); // hand列表下标
  const [webData, setWebData] = useState([]); // web数据
  const [handData, setHandData] = useState([]); // 手持数据
  const [visible, setVisible] = useState(false); // 弹窗
  const [flag, setFlag] = useState(0); // 更新list
  const [handStatus, setHandStatus] = useState([]); // 更新状态
  const [webStatus, setWebStatus] = useState([]); // 更新状态
  const [type, setType] = useState(''); // 弹窗类型
  const [checkLoading, setCheckLoading] = useState(false);
  const [formObj, setFormObj] = useState({ user: 'admin', password: 'geoserver' });
  const [tree, setTree] = useState([]);
  const [leafs, setLeafs] = useState([]);
  const [addVisible, setAddVisible] = useState(false);
  const [checkValue, setCheckValue] = useState([]);

  const columns = [
    {
      title: '默认方案',
      align: 'center',
      key: 'url',
      render: (text, record, index) => (
        <Space>
          <Checkbox
            checked={webStatus[index + webCurrent * 5]}
            onChange={e => {
              onChangeCheck(e, record, index + webCurrent * 5);
            }}
          />
        </Space>
      ),
    },
    {
      title: '方案名',
      dataIndex: 'schemename',
      key: 'schemename',
      align: 'center',
    },
    {
      title: '关联角色',
      align: 'center',
      key: 'type',
      render: record => (
        <Space size="middle">
          <UserAddOutlined
            onClick={() => pickRole(record)}
            style={{ fontSize: '18px', color: '#1890FF' }}
          />
        </Space>
      ),
    },
    {
      title: '编辑',
      align: 'center',
      key: 'schemename',
      render: (text, record, index) => (
        <Space>
          <div onClick={e => e.stopPropagation()}>
            <Popconfirm
              title="是否删除此条方案?"
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                delWebConfirm(record);
              }}
            >
              <Button size="small" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        </Space>
      ),
    },
  ];
  const columns1 = [
    {
      title: '查询方案',
      align: 'center',
      key: 'url',
      render: (text, record, index) => (
        <Space>
          <Checkbox
            checked={handStatus[index + handCurrent * 5]}
            onChange={e => {
              onChangeHand(e, record, index + handCurrent * 5);
            }}
          />
        </Space>
      ),
    },
    {
      title: '方案名',
      dataIndex: 'schemename',
      key: 'schemename',
      align: 'center',
    },
    {
      title: '关联角色',
      align: 'center',
      key: 'type',
      render: record => (
        <Space size="middle">
          <UserAddOutlined
            onClick={() => pickRole(record)}
            style={{ fontSize: '18px', color: '#1890FF' }}
          />
        </Space>
      ),
    },
    {
      title: '编辑',
      align: 'center',
      key: 'schemename',
      render: (text, record, index) => (
        <Space>
          <div onClick={e => e.stopPropagation()}>
            <Popconfirm
              title="是否删除此条方案?"
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                delhandConfirm(record);
              }}
            >
              <Button size="small" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        </Space>
      ),
    },
  ];
  // 获取选中的角色
  const onPushSubmit = value => {
    setAddVisible(false);
    if (value.length) {
      let query = {
        schemename: record.schemename,
        terminalType: record.isStatus,
        isBaseMap: false,
        jsonCfg: JSON.stringify({
          roles: value.join(','),
        }),
      };
      SetServiceConfig(query)
        .then(res => {
          if (res.code == 0) {
            prompt('success', '关联角色成功');
            setFlag(flag + 1);
          } else {
            prompt('fail', '关联角色失败');
          }
        })
        .catch(err => {
          prompt('fail', '网络请求失败');
        });
    }
  };
  const rolCallBack = useCallback(list => {
    let strList = [];
    if (list.length > 0) {
      list.forEach(item => {
        console.log(item, 'item');
        Object.keys(item.last).forEach(i => {
          strList.push(i);
        });
      });
      console.log(strList);
      onPushSubmit(strList);
    }
  });

  // 获取角色
  const pickRole = e => {
    setRecord(e);
    setAddVisible(true);
    console.log(tree);
    console.log(leafs);
    let arr = e.roles != null ? e.roles.split(',') : [];
    console.log(arr);
    setCheckValue(arr);
  };
  // 设置web方案
  const onChangeCheck = (e, record, index) => {
    console.log(e);
    console.log(record);
    console.log(index);
    setCheckLoading(true);
    console.log(webStatus);
    const newLoadings = [...webStatus];
    newLoadings.map((item, loadIndex) =>
      loadIndex == index
        ? (newLoadings[loadIndex] = !newLoadings[loadIndex])
        : (newLoadings[loadIndex] = false),
    );
    console.log(newLoadings);
    setWebStatus(newLoadings);
    let query = {
      schemename: record.schemename,
      type: 'web',
      uncheck: true,
    };
    // 取消默认
    if (!newLoadings[index]) {
      SetDefaultsSchemeName(query).then(res => {
        setCheckLoading(false);
        if (res.code == 0) {
          const changehandData = [...webData];
          changehandData[index].type = 'dynamic';
          console.log(changehandData);
          setWebData(changehandData);

          prompt('success', '设置成功');
        } else {
          prompt('fail', `${record.schemename}默认设置时遇到错误:${res.message}`);
        }
      });
      return;
    }
    // 设置默认
    let beforeDefault = webData.findIndex(item => item.type == 'pipenet');
    SetDefaultsSchemeName({
      schemename: record.schemename,
      type: 'web',
      uncheck: false,
    }).then(res => {
      setCheckLoading(false);
      if (res.code == 0) {
        const changehandData = [...webData];
        changehandData[index].type = 'pipenet';
        console.log(changehandData);
        setWebData(changehandData);
        // 设置默认的同时取消另一个默认
        // if (beforeDefault != -1) {
        //   SetDefaultsSchemeName({
        //     schemename: changehandData[beforeDefault].schemename,
        //     type: 'web',
        //     uncheck: true,
        //   }).then(resdata => {
        //     setCheckLoading(false);
        //     if (resdata.code == 0) {
        //       const changehandData1 = [...webData];
        //       changehandData1[beforeDefault].type = 'dynamic';
        //       console.log(changehandData1);
        //       setWebData(changehandData1);
        //       prompt('success', '设置成功');
        //       // return;
        //     } else {
        //       prompt('fail', `${record.schemename}默认设置时遇到错误:${res.message}`);
        //     }
        //   });
        // } else {
        //   prompt('success', '设置成功');
        // }
        prompt('success', '设置成功');
      }
    });
  };

  // 无选中值时的默认值
  const onChangeCheck1 = (e, record, index, aa) => {
    console.log(aa);
    console.log(webStatus);
    setCheckLoading(true);
    const newLoadings = [...aa];
    let query = {
      schemename: record.schemename,
      type: 'web',
      uncheck: true,
    };
    if (!newLoadings[index]) {
      SetDefaultsSchemeName(query).then(res => {
        setCheckLoading(false);
        if (res.code == 0) {
          const changehandData = [...webData];
          changehandData[index].type = 'dynamic';
          // setWebData(changehandData);
          prompt('success', '设置成功');
        } else {
          prompt('fail', `${record.schemename}默认设置时遇到错误:${res.message}`);
        }
      });
      return;
    }
    let beforeDefault = webData.findIndex(item => item.type == 'pipenet');
    SetDefaultsSchemeName({
      schemename: record.schemename,
      type: 'web',
      uncheck: false,
    }).then(res => {
      setCheckLoading(false);
      if (res.code == 0) {
        const changehandData = [...webData];
        changehandData[index].type = 'pipenet';
        // setWebData(changehandData);

        // if (beforeDefault != -1) {
        //   SetDefaultsSchemeName({
        //     schemename: changehandData[beforeDefault].schemename,
        //     type: 'web',
        //     uncheck: true,
        //   }).then(resdata => {
        //     setCheckLoading(false);
        //     if (resdata.code == 0) {
        //       const changehandData1 = [...webData];
        //       changehandData1[beforeDefault].type = 'dynamic';
        //       // setWebData(changehandData1);
        //       prompt('success', '设置成功');
        //     } else {
        //       prompt('fail', `${record.schemename}默认设置时遇到错误:${res.message}`);
        //     }
        //   });
        // } else {
        //   prompt('success', '设置成功');
        // }
        prompt('success', '设置成功');
      }
    });
  };

  // 选择手持方案
  const onChangeHand = (e, record, index) => {
    setCheckLoading(true);
    const newLoadings = [...handStatus];
    newLoadings.map((item, loadIndex) =>
      loadIndex == index
        ? (newLoadings[loadIndex] = !newLoadings[loadIndex])
        : (newLoadings[loadIndex] = false),
    );
    setHandStatus(newLoadings);
    let query = {
      schemename: record.schemename,
      type: 'phone',
      uncheck: true,
    };
    if (!newLoadings[index]) {
      SetDefaultsSchemeName(query).then(res => {
        setCheckLoading(false);
        if (res.code === 0) {
          const changehandData = [...handData];
          changehandData[index].isDefault = false;
          setHandData(changehandData);
          prompt('success', '设置成功');
        } else {
          prompt('fail', `${record.schemename}默认设置时遇到错误:${res.message}`);
        }
      });
      return;
    }
    let beforeDefault = handData.findIndex(item => item.isDefault);
    SetDefaultsSchemeName({
      schemename: record.schemename,
      type: 'phone',
      uncheck: false,
    }).then(res => {
      setCheckLoading(false);
      if (res.code === 0) {
        const changehandData = [...handData];
        changehandData[index].isDefault = true;
        setHandData(changehandData);
        // if (beforeDefault != -1) {
        //   SetDefaultsSchemeName({
        //     schemename: changehandData[beforeDefault].schemename,
        //     type: 'phone',
        //     uncheck: true,
        //   }).then(resdata => {
        //     setCheckLoading(false);
        //     if (resdata.code == 0) {
        //       const changehandData1 = [...handData];
        //       changehandData1[beforeDefault].isDefault = false;
        //       setHandData(changehandData1);
        //       prompt('success', '设置成功');
        //       // return;
        //     } else {
        //       prompt('fail', `${record.schemename}默认设置时遇到错误:${res.message}`);
        //     }
        //   });
        // } else {
        //   prompt('success', '设置成功');
        // }
        prompt('success', '设置成功');
      }
    });
  };

  // 选择手持方案
  const onChangeHand1 = (e, record, index, aa) => {
    setCheckLoading(true);
    const newLoadings = [...aa];
    let query = {
      schemename: record.schemename,
      type: 'phone',
      uncheck: true,
    };
    if (!newLoadings[index]) {
      SetDefaultsSchemeName(query).then(res => {
        setCheckLoading(false);
        if (res.code === 0) {
          const changehandData = [...handData];
          changehandData[index].isDefault = false;
          // setHandData(changehandData);
          prompt('success', '设置成功');
        } else {
          prompt('fail', `${record.schemename}默认设置时遇到错误:${res.message}`);
        }
      });
      return;
    }
    let beforeDefault = handData.findIndex(item => item.isDefault);
    SetDefaultsSchemeName({
      schemename: record.schemename,
      type: 'phone',
      uncheck: false,
    }).then(res => {
      setCheckLoading(false);
      if (res.code === 0) {
        const changehandData = [...handData];
        changehandData[index].isDefault = true;
        // setHandData(changehandData);
        // if (beforeDefault != -1) {
        //   SetDefaultsSchemeName({
        //     schemename: changehandData[beforeDefault].schemename,
        //     type: 'phone',
        //     uncheck: true,
        //   }).then(resdata => {
        //     setCheckLoading(false);
        //     if (resdata.code == 0) {
        //       const changehandData1 = [...handData];
        //       changehandData1[beforeDefault].isDefault = false;
        //       // setHandData(changehandData1);
        //       prompt('success', '设置成功');
        //       // return;
        //     } else {
        //       prompt('fail', `${record.schemename}默认设置时遇到错误:${res.message}`);
        //     }
        //   });
        // } else {
        //   prompt('success', '设置成功');
        // }
        prompt('success', '设置成功');
      }
    });
  };
  const prompt = (type, content) => {
    if (type == 'success') {
      notification.success({
        message: '提示',
        duration: 3,
        description: content,
      });
    } else {
      notification.error({
        message: '提示',
        duration: 3,
        description: content,
      });
    }
  };
  const onSubmit = prop => {
    setVisible(false);
    if (type == 'add') {
      renderTileWeb();
    } else {
      renderTile();
    }
    // setFlag(flag + 1);
  };
  // 删除web配置方案
  const delWebConfirm = record => {
    deleteConfig({
      schemename: record.schemename,
      terminalType: 'web',
      isBaseMap: false,
    }).then(res => {
      if (res.msg === 'Ok') {
        prompt('success', '删除成功');
        setFlag(flag + 1);
      } else {
        prompt('fail', '删除失败');
      }
    });
  };
  // 删除手持配置方案
  const delhandConfirm = e => {
    setCheckLoading(true);
    deleteConfig({
      schemename: e.schemename,
      terminalType: 'phone',
      isBaseMap: false,
    }).then(res => {
      setCheckLoading(false);
      if (res.msg === 'Ok') {
        prompt('success', '删除成功');
        setFlag(flag + 1);
      } else {
        prompt('fail', '删除失败');
      }
    });
  };
  // 添加方案
  const addType = type => {
    setType(type);
    let listData = [];
    type == 'add' ? (listData = webData) : (listData = handData);
    let webSchemenameArr = [];
    let schemeArr = [];
    setTreeLoading(true);
    GetMaplayerByTerminalType({
      terminalType: 'scheme',
      isBaseMap: false,
    }).then(res => {
      if (res.data.scheme && res.data.scheme.optionalLayer.layers.length) {
        setTreeLoading(false);
        listData.map(item => {
          webSchemenameArr.push(item.schemename);
        });
        res.data.scheme.optionalLayer.layers.map(item => {
          if (!webSchemenameArr.includes(item.schemename)) schemeArr.push(item.schemename);
        });
        setSchemename(schemeArr);
        if (schemeArr.length) {
          setVisible(true);
        } else {
          notification.warning({
            message: '提示',
            duration: 3,
            description: '请先配置方案',
          });
        }
      } else {
        setTreeLoading(false);
        notification.warning({
          message: '提示',
          duration: 3,
          description: '请先配置方案',
        });
      }
    });
  };
  useEffect(() => {
    console.log(flag);
    renderTile();
    renderTileWeb();
  }, [flag]);
  // 获取瓦片数据配置数据
  const renderTile = () => {
    setCheckLoading(true);
    // 查询手持方案
    let schemeConfigQueryRequest = GetMaplayerByTerminalType({
      terminalType: 'phone',
      isBaseMap: false,
    });
    Promise.all([schemeConfigQueryRequest])
      .then(res => {
        console.log('res', res);
        if (res[0].msg === 'Ok' && res[0].data.phone) {
          let arr = [];
          res[0].data.phone.optionalLayer.layers.map((item, index) => {
            if (item.isDefault) {
              arr.push(true);
            } else {
              arr.push(false);
            }
            item.isStatus = 'phone';
            return item;
          });
          setHandData(res[0].data.phone.optionalLayer.layers);
          if (arr.indexOf(true) == -1) {
            arr[arr.length - 1] = true;
            setHandStatus(arr);
            onChangeHand1(
              '',
              res[0].data.phone.optionalLayer.layers[arr.length - 1],
              arr.length - 1,
              arr,
            );
          } else {
            setHandStatus(arr);
          }
        }
        setCheckLoading(false);
      })
      .catch(e => {
        setCheckLoading(false);
      });
  };

  // 获取瓦片数据配置数据
  const renderTileWeb = () => {
    setCheckLoading(true);
    // 查询web方案
    let webSchemeQueryRequest = GetMaplayerByTerminalType({
      terminalType: 'web',
      isBaseMap: false,
    });
    Promise.all([webSchemeQueryRequest])
      .then(res => {
        console.log('res', res);
        if (res[0].msg === 'Ok' && res[0].data.web) {
          let arr = [];
          res[0].data.web.optionalLayer.layers.map((item, index) => {
            if (item.type === 'pipenet') {
              arr.push(true);
            } else {
              arr.push(false);
            }
            item.isStatus = 'web';
            return item;
          });
          console.log(res[0].data.web.optionalLayer.layers);
          setWebData(res[0].data.web.optionalLayer.layers);
          if (arr.indexOf(true) == -1) {
            arr[arr.length - 1] = true;
            setWebStatus(arr);
            onChangeCheck1(
              '',
              res[0].data.web.optionalLayer.layers[arr.length - 1],
              arr.length - 1,
              arr,
            );
          } else {
            setWebStatus(arr);
          }
        }
        setCheckLoading(false);
      })
      .catch(e => {
        setCheckLoading(false);
      });
  };

  return (
    <div className={styles.solutionContainer}>
      <Spin tip="loading..." spinning={checkLoading}>
        <div style={{ height: 'calc(100vh - 150px)', width: '100%', overflow: 'scroll' }}>
          <Divider orientation="left">
            <div className={styles.divider}>
              {' '}
              Web{' '}
              <PlusOutlined
                onClick={() => {
                  addType('add');
                }}
                className={styles.dividerIcon}
              />
            </div>
          </Divider>
          <Table
            columns={columns}
            dataSource={webData}
            bordered
            // style={{ height: 'calc(100vh - 610px)' }}
            pagination={false}
            rowKey="schemename"
            scroll={{ y: 250 }}
          />

          <Divider orientation="left">
            <div className={styles.divider}>
              Moblie{' '}
              <PlusOutlined
                onClick={() => {
                  addType('addHand');
                }}
                className={styles.dividerIcon}
              />
            </div>{' '}
          </Divider>
          <Table
            columns={columns1}
            dataSource={handData}
            bordered
            rowKey="schemename"
            scroll={{ y: 250 }}
            // style={{ height: 'calc(100vh - 610px)' }}
            pagination={false}
          />
        </div>
      </Spin>
      <AddModal
        visible={visible}
        onCancel={() => setVisible(false)}
        callBackSubmit={onSubmit}
        type={type}
        formObj={formObj}
        listData={schemename}
      />
      {/* <VisibleRoleModal
        visible={addVisible}
        onCancel={() => setAddVisible(false)}
        onSubmit={onPushSubmit}
        title="关联角色"
        initValues={checkValue}
        tree={tree}
        leafs={leafs}
      /> */}
      <RoleModal
        selectValue={checkValue.toString()}
        visible={addVisible}
        rolCallBack={roleList => rolCallBack(roleList)}
        onCancel={() => {
          setAddVisible(false);
        }}
      />
    </div>
  );
};
export default VectorData;