/* eslint-disable no-unneeded-ternary */
/* eslint-disable no-return-assign */
import { Space, Table, Button, Popconfirm, notification, Divider, Checkbox, Spin } from 'antd';
import React, { useState, useEffect, useCallback } from 'react';
import { PlusOutlined, UserAddOutlined } from '@ant-design/icons';
import RMSComponents from '@/components/RolePmSite/index';
import styles from '../SchemeConfig.less';
import {
  deleteConfig,
  SetServiceConfig,
  GetMaplayerByTerminalType,
  SetDefaultsSchemeName,
} from '@/services/webConfig/api';
import AddModal from './AddModal';
const VectorData = props => {
  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 [addVisible, setAddVisible] = useState(false);
  const [checkValue, setCheckValue] = useState([]);
  const [gisType, setGisType] = useState('');

  const columns = [
    {
      title: '默认方案',
      align: 'center',
      key: 'url',
      render: (text, record, index) => (
        <Space>
          <Checkbox
            checked={webStatus[index + webCurrent * 5]}
            onChange={e => {
              onChangeCheck(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);
              setGisType('web');
            }}
            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(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);
              setGisType('phone');
            }}
            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);

    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 => {
    onPushSubmit(list.ids);
  });

  // 获取站点
  const pickRole = e => {
    setRecord(e);
    setAddVisible(true);
    let arr = e.roles != null ? e.roles.split(',') : [];
    setCheckValue(arr);
  };
  // 设置web方案
  const onChangeCheck = (record, index, aa, newData) => {
    setCheckLoading(true);
    const newLoadings = aa ? [...aa] : [...webStatus];
    if (!aa) {
      newLoadings.map((item, loadIndex) =>
        loadIndex == index
          ? (newLoadings[loadIndex] = !newLoadings[loadIndex])
          : (newLoadings[loadIndex] = false),
      );
      setWebStatus(newLoadings);
    }
    let query = {
      schemename: record.schemename,
      type: 'web',
      uncheck: !newLoadings[index] ? true : false,
    };
    // 取消默认
    SetDefaultsSchemeName(query)
      .then(res => {
        setCheckLoading(false);
        if (res.code == '0') {
          const changehandData = newData ? [...newData] : [...webData];
          changehandData[index].type = !newLoadings[index] ? 'dynamic' : 'pipenet';
          setWebData(changehandData);
          prompt('success', '设置成功');
        } else {
          prompt('fail', `${record.schemename}默认设置时遇到错误：${res.message}`);
        }
      })
      .catch(err => {
        setCheckLoading(false);
        if (err.message.indexOf('timeout') !== -1) {
          notification.error({
            message: '提示',
            duration: 3,
            description: '请求超时',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: err.message,
          });
        }
      });
  };

  // 选择手持方案
  const onChangeHand = (record, index, aa, newData) => {
    setCheckLoading(true);
    const newLoadings = aa ? [...aa] : [...handStatus];
    if (!aa) {
      newLoadings.map((item, loadIndex) =>
        loadIndex == index
          ? (newLoadings[loadIndex] = !newLoadings[loadIndex])
          : (newLoadings[loadIndex] = false),
      );
      setHandStatus(newLoadings);
    }
    let query = {
      schemename: record.schemename,
      type: 'phone',
      uncheck: !newLoadings[index] ? true : false,
    };
    SetDefaultsSchemeName(query)
      .then(res => {
        setCheckLoading(false);
        if (res.code == '0') {
          const changehandData = newData ? [...newData] : [...handData];
          changehandData[index].isDefault = !newLoadings[index] ? false : true;
          setHandData(changehandData);
          prompt('success', '设置成功');
        } else {
          prompt('fail', `${record.schemename}默认设置时遇到错误：${res.message}`);
        }
      })
      .catch(err => {
        setCheckLoading(false);
        if (err.message.indexOf('timeout') !== -1) {
          notification.error({
            message: '提示',
            duration: 3,
            description: '请求超时',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: err.message,
          });
        }
      });
  };

  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.code == '0') {
        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.code == '0') {
        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 = [];
    GetMaplayerByTerminalType({
      terminalType: 'scheme',
      isBaseMap: false,
    })
      .then(res => {
        if (res.data && res.data.length > 0) {
          listData.map(item => {
            webSchemenameArr.push(item.schemename);
          });
          res.data.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 {
          notification.warning({
            message: '提示',
            duration: 3,
            description: '暂无可用方案，请先配置方案',
          });
        }
      })
      .catch(err => {
        if (err.message.indexOf('timeout') !== -1) {
          notification.error({
            message: '提示',
            duration: 3,
            description: '请求超时',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: err.message,
          });
        }
      });
  };

  useEffect(() => {
    renderTile();
    renderTileWeb();
  }, [flag]);

  // 获取瓦片数据配置数据
  const renderTile = () => {
    setCheckLoading(true);
    // 查询手持方案
    let schemeConfigQueryRequest = GetMaplayerByTerminalType({
      terminalType: 'phone',
      isBaseMap: false,
    });
    Promise.all([schemeConfigQueryRequest])
      .then(res => {
        setCheckLoading(false);
        if (res[0].code == '0') {
          let arr = [];
          res[0].data.optionalLayer.layers.map((item, index) => {
            if (item.isDefault) {
              arr.push(true);
            } else {
              arr.push(false);
            }
            item.isStatus = 'phone';
            return item;
          });
          setHandData(res[0].data.optionalLayer.layers);
          if (arr.indexOf(true) == -1 && arr.length > 0) {
            arr[arr.length - 1] = true;
            setHandStatus(arr);
            onChangeHand(
              res[0].data.optionalLayer.layers[arr.length - 1],
              arr.length - 1,
              arr,
              res[0].data.optionalLayer.layers,
            );
          } else {
            setHandStatus(arr);
          }
        }
      })
      .catch(err => {
        setCheckLoading(false);
        if (err.message.indexOf('timeout') !== -1) {
          notification.error({
            message: '提示',
            duration: 3,
            description: '请求超时',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: err.message,
          });
        }
      });
  };

  // 获取瓦片数据配置数据
  const renderTileWeb = () => {
    setCheckLoading(true);
    // 查询web方案
    let webSchemeQueryRequest = GetMaplayerByTerminalType({
      terminalType: 'web',
      isBaseMap: false,
    });
    Promise.all([webSchemeQueryRequest])
      .then(res => {
        setCheckLoading(false);
        if (res[0].code == '0') {
          let arr = [];
          res[0].data.optionalLayer.layers.map((item, index) => {
            if (item.type === 'pipenet') {
              arr.push(true);
            } else {
              arr.push(false);
            }
            item.isStatus = 'web';
            return item;
          });
          setWebData(res[0].data.optionalLayer.layers);
          if (arr.indexOf(true) == -1 && arr.length > 0) {
            arr[arr.length - 1] = true;
            setWebStatus(arr);
            onChangeCheck(
              res[0].data.optionalLayer.layers[arr.length - 1],
              arr.length - 1,
              arr,
              res[0].data.optionalLayer.layers,
            );
          } else {
            setWebStatus(arr);
          }
        }
      })
      .catch(err => {
        setCheckLoading(false);
        if (err.message.indexOf('timeout') !== -1) {
          notification.error({
            message: '提示',
            duration: 3,
            description: '请求超时',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: err.message,
          });
        }
      });
  };

  return (
    <div className={styles.solutionContainer}>
      <Spin tip="loading..." spinning={checkLoading}>
        <div
          className={styles.tableContainer}
          style={{ height: 'calc(100vh - 150px)', width: '100%', overflow: 'scroll' }}
        >
          <div className={styles.tableContent}>
            <Divider orientation="left">
              <div className={styles.divider}>
                Web
                <PlusOutlined
                  onClick={() => {
                    addType('add');
                  }}
                  className={styles.dividerIcon}
                />
              </div>
            </Divider>
            <Table
              columns={columns}
              dataSource={webData}
              bordered
              pagination={false}
              rowKey="schemename"
              scroll={{ y: 600 }}
            />
          </div>
          <div className={styles.tableContent}>
            <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: 600 }}
              pagination={false}
            />
          </div>
        </div>
      </Spin>
      <AddModal
        visible={visible}
        onCancel={() => setVisible(false)}
        callBackSubmit={onSubmit}
        type={type}
        formObj={formObj}
        listData={schemename}
      />
      <RMSComponents
        visible={addVisible}
        onCancel={() => {
          setAddVisible(false);
        }}
        callBackSubmit={roleList => rolCallBack(roleList)}
        newCheckedList={checkValue.toString().split(',')} // 单选框中的值
        groupName="站点" // 打开组件展示的分组名，用来首次获取数据
        chooseGroupName={['站点']} // 可选分组名
        dataType="id"
        mapSite={true}
        gisType={gisType}
        // isRadio={true} // 站点单选
      />
    </div>
  );
};
export default VectorData;
