/**
 * 钟是志
 * 2022年5月25日
 * openSelectFieldsModal 弹窗
 */
import React, { useEffect, useState } from 'react';
import { isJSON } from '@/webPublic/one_stop_public/copy';
import { Checkbox, Col, Modal, Row, message } from 'antd';
import ButtonDiy from '@/webPublic/one_stop_public/App/ButtonDiy/ButtonDiy';
import styles from './style.less';

export default function SelectModal({
                                      custom,
                                      index,
                                      show,
                                      changeShow,
                                      downloadFile,
                                    }) {

  const [fields, setFields] = useState([]);
  const [buttonName, setButtonName] = useState('全部选中');
  const [strInput, setStrInput] = useState([]);
  const [inputDisable, setInputDisable] = useState(false); // 点击全部选中整族失效
  useEffect(() => {
    if (isJSON(custom)) {
      let exportConfig = JSON.parse(custom)?.exportConfig;
      if (exportConfig && exportConfig.length > index && index >= 0) {
        setFields(exportConfig[index].fields);
      }
    }

  }, [custom]);

  const arrayChange = (checkedValues) => {
    setStrInput(checkedValues);
  };

  const selectAllAndCancelAll = () => {
    const all = fields.map(item => item.k);
    if (strInput.length === all.length) {
      setStrInput([]);
      setButtonName('全部选中');
    } else {
      setStrInput(all);
      setButtonName('全部取消');
    }
  };

  const handleOk = () => {
    if (!strInput || !strInput.length) {
      message.warning('请选择导出的列');
      return false;
    }
    const newFileds = fields.filter((item) => {
      return strInput.includes(item.k);
    });
    if (!newFileds || !newFileds.length) {
      changeShow();
      return false;
    }
    const newCustom = JSON.parse(custom);
    newCustom.exportConfig[index].fields = newFileds;
    const newParams = {
      ...show.param,
      custom: JSON.stringify(newCustom),
    };
    downloadFile(show.downloadUrl, newParams);
  };

  return !!show && <Modal
    title={'请选择导出列'}
    visible={true}
    onOk={handleOk}
    onCancel={changeShow}
    width={900}
  >
    <Row>
      <Col span={4}>导出列数据
        <Col>
          <ButtonDiy
            name={buttonName}
            handleClick={selectAllAndCancelAll}
          />
        </Col>
      </Col>
      <Col span={20}>
        <div className={styles.formbody}>
          <Checkbox.Group
            options={fields.map((g) => {
              return {
                label: g.n,
                value: g.k,
              };
            })}
            onChange={arrayChange}
            value={strInput}
            disabled={inputDisable}
          />
        </div>
      </Col>
    </Row>
  </Modal>;
}
