import React from 'react';
import { connect } from 'dva';
import { Card, Input, message, Modal } from 'antd';
import { EditableDataTable, FormEL, UploadEL } from '@components';
import { dataUtils, enums, formUtils } from '@utils';
import { Toolbar, RichText } from '@bizComponents';

const { TextArea } = Input;
const { customMsg } = enums;
const confirm = Modal.confirm;
const Detail = ({ contractTmplDetail, dispatch, loading }) => {
  const {
    mode,
    formData,
    list,
    modelContent,
    saveBtnFlag,
    readOnly
  } = contractTmplDetail;
  const { id, attachRepo } = formData;
  const dataKey = id ? id : '';

  const domain = 'contractTmplDetail';
  const domainCN = '合同模板';

  // 返回
  const handleCancel = () => {
    dispatch({ type: `${domain}/cancel` });
  };

  // 模板标题样式
  const formItemLayout = {
    colon: false,
    labelCol: {
      span: 3
    },
    wrapperCol: {
      span: 15
    },
    style: {}
  };

  const colProps = {
    xs: 18,
    sm: 18,
    md: 18,
    xl: 18
  };

  // 模板标题
  const basic = [
    {
      title: '合同模板标题:',
      dataIndex: 'contractModelName',
      tag: <Input disabled={readOnly} />,
      options: {
        rules: [
          {
            required: true,
            message: '必填'
          },
          {
            min: 1,
            max: 100,
            message: '不能超过100个字'
          }
        ]
      }
    }
  ];

  // 模板标题变更
  const handleFormChange = field => {
    const key = Object.keys(field)[0];
    dispatch({
      type: `${domain}/updateForm`,
      payload: {
        key,
        value: field[key]
      }
    });
  };

  // 富文本插入合同变量
  const insertContactVar = contractVal => {
    // 是否已有此变量
    const inserted = list.find(
      m => m.contractVarName === contractVal.contractVarName
    );
    if (!inserted) {
      // 插入富文本
      this.editorInstance.editor.execCommand(
        'inserthtml',
        `${contractVal.contractVarName}`
      );
      // 插入变量列表
      dispatch({
        type: `${domain}/addRow`,
        payload: {
          id: dataUtils.getRandomInt(-99999999, -1),
          ...contractVal
        }
      });
    } else {
      message.info('已使用此变量');
    }
  };

  // 富文本配置
  const editorProps = {
    value: modelContent, // 初始内容
    readOnly, // 只读
    contractVarCfg: {
      title: '合同变量',
      onselect: insertContactVar
    }
  };

  // 模板变量 - 字段更新
  const handleChange = (key, index, newValue) => {
    dispatch({
      type: `${domain}/updateCell`,
      payload: { key, index, value: newValue }
    });
  };

  // 删除变量
  const handleDelete = (selectedKeys, selectedRows) => {
    let htmlContent = this.editorInstance.editor.getContent();
    selectedRows.map(item => {
      while (
        item.contractVarName &&
        htmlContent.includes(item.contractVarName)
      ) {
        htmlContent = htmlContent.replace(item.contractVarName, '');
      }
    });
    this.editorInstance.editor.setContent(htmlContent);
    dispatch({
      type: `${domain}/deleteRow`,
      payload: {
        selectedKeys
      }
    });
  };

  // 变量维护
  const contractTmplTableProps = {
    rowKey: 'id',
    scroll: {
      x: '100%'
    },
    domain,
    dispatch,
    loading,
    dataSource: list,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    columns: [
      {
        title: '变量名称',
        dataIndex: 'contractVarName',
        width: '20%',
        render: (value, row, index) => {
          return (
            <Input
              disabled={true}
              value={value}
              onChange={e => {
                handleChange('contractVarName', index, e.target.value);
              }}
            />
          );
        }
      },
      {
        title: '变量说明(100字以内)',
        dataIndex: 'contractVarDesc',
        required: true,
        width: '60%',
        render: (value, row, index) => {
          return (
            <TextArea
              autosize={true}
              disabled={readOnly || !row.settled}
              value={row.settled ? value : row.contractVarDesc}
              onChange={e => {
                handleChange('contractVarDesc', index, e.target.value);
              }}
            />
          );
        }
      }
    ],

    buttons: [
      {
        key: 'cancel',
        type: 'primary',
        name: '删除',
        requiredSelected: 2,
        hidden: readOnly,
        cb: (selectedRowKeys, selectedRows) => {
          confirm({
            title: '确定要删除所选变量吗?',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
              handleDelete(selectedRowKeys, selectedRows);
            }
          });
        }
      }
    ]
  };

  const getDefaultValues = () => {
    const init = {};
    basic.forEach(item => {
      if (item.options && item.options.initialValue) {
        init[item.dataIndex] = item.options.initialValue;
      }
    });
    return init;
  };

  const handleAll = () => {
    const htmlContent = this.editorInstance.editor.getContent();
    formUtils.validateForm(
      [...basic],
      Object.assign(getDefaultValues(), formData),
      () => {
        let count = 0;
        for (const item of list) {
          if (!item.contractVarDesc || !item.contractVarDesc.trim()) {
            message.warn(
              customMsg.CONTRACT_ITEM_CONTENT +
                item.contractVarName +
                customMsg.CONTRACT_CHECK_NULL
            );
            return;
          }
          if (item.contractVarDesc.length > 100) {
            message.warn(
              customMsg.CONTRACT_ITEM_CONTENT +
                item.contractVarName +
                customMsg.CONTRACT_VAR_DESC_CHECK_LENGTH
            );
            return;
          }
          count += 1;
        }
        if (count === list.length) {
          dispatch({
            type: `${domain}/save`,
            payload: {
              modelContent: htmlContent
            }
          });
        } else {
          message.warn(
            customMsg.CONTRACT_ITEM_CONTENT +
              customMsg.CONTRACT_VAR_DESC +
              customMsg.CONTRACT_CHECK_FAIL
          );
        }
      }
    );
  };

  const buttons = [
    {
      id: 'save',
      text: '保存',
      type: 'primary',
      hidden: !saveBtnFlag || readOnly,
      onClick: () => {
        handleAll();
      }
    }
  ];

  return (
    <div>
      <Toolbar
        domain={domain}
        loading={loading}
        formData={formData}
        readOnly={true}
        mode={mode}
        buttons={buttons}
        handleCancel={handleCancel}
      />

      <Card loading={loading.effects[`${domain}/query`]} id="tmphead">
        <FormEL
          items={basic}
          record={formData}
          onFieldsChange={handleFormChange}
          formItemLayout={formItemLayout}
          ColProps={colProps}
        />
      </Card>

      <Card title="合同模板附件" id="contractSfs">
        {attachRepo && <UploadEL
          api={`/api/contract-mgmt/contract-tmpls/sfs/token?clsPath=${attachRepo}&dataKey=${dataKey}`}
          dataKey={dataKey}
          listTypes={'text'}
          disabled={readOnly}
        />}
      </Card>

      <Card
        loading={
          loading.effects[
            mode === 'create' ? `${domain}/newCreate` : `${domain}/query`
          ]
        }
        id="tmpbody"
        style={{ height: '100%' }}
      >
        <RichText
          {...editorProps}
          ref={instance => (this.editorInstance = instance)}
        />
      </Card>

      <Card title="模板变量" id="varMaintain">
        <EditableDataTable {...contractTmplTableProps} />
      </Card>
    </div>
  );
};

export default connect(({ contractTmplDetail, loading }) => ({
  contractTmplDetail,
  loading
}))(Detail);
