import React, { Component } from 'react';
import {
  WeaDialog,
  WeaRightMenu,
  WeaLocaleProvider,
  WeaFormItem,
  WeaSearchGroup,
  WeaTools,
} from 'ecCom';
import {
  Button,
} from 'antd';
import { 
  WeaForm, 
  WeaSwitch,
} from "comsMobx";

const {getLabel} = WeaLocaleProvider;

// 附件设置
export default class Ftp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showAttachmentSetForm: false,
      requireFlag: {
        position: "absolute",
        top: "50%",
        width: 9,
        height: 9,
        marginTop: -5,
        marginLeft: 5,
        color: "transparent",
        backgroundImage: `url(${window.ecologyContentPath || ""}/images/BacoError_wev9.png)`,
        backgroundRepeat: "no-repeat",
        backgroundPosition: "50%",
      },
      detailAttachmentSetForm: new WeaForm(),
    }
  }

  render() {
    const {
      showAttachmentSetForm,
      detailAttachmentSetForm,
    } = this.state;

    return (<div style={{position: "relative"}}>
      <Button 
        ecId={`${this && this.props && this.props.ecId || ''}_Button@ts379s`} 
        size={'small'} 
        onClick={this.handleClickSetAttachment}
      >{getLabel('30747','设置')}</Button>
      {this.hasValueFlag()}

      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@4k04ji`}
        title={getLabel(23796,'附件设置')}
        moduleName="integration"
        visible={showAttachmentSetForm}
        hasScroll={true}
        style={{width: 700, height: 600}}
        onCancel={this.closeDialog}
        buttons={this.getButtons()}
        moreBtn={{
          datas: this.getAttachmentBtn(),
          collectParams: []
        }}
      >
        <WeaRightMenu 
          ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@kw70dv`} 
          datas={this.getAttachmentBtn()} 
          collectParams={[]}
        >
          {
            detailAttachmentSetForm.render({col: 1, center: true}, {}, true, (item, index) => {
              if(index == 1) {
                let items = [];
                item && item.items && item.items.forEach(field => {
                  items.push({
                    com: (<div style={{margin: "0 20px 0 -20px"}}>
                      <WeaFormItem 
                        ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@66fkqc@integrationWorkflowTriggerForm${field.domkey[0]}`}
                        labelCol={{span: 0}}
                        wrapperCol={{span: 24}}
                        error={detailAttachmentSetForm.getError(field)}
                        tipPosition="bottom"
                      >
                        <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ew89bq@integrationWorkflowTriggerForm${field.domkey[0]}`} form={detailAttachmentSetForm} fieldConfig={field} />
                      </WeaFormItem>
                    </div>)
                  })
                })
                return <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@nfyaqv`} col={1} items={items} title={item.title} showGroup={item.defaultshow} needTrigger={item.defaultshow} />
              }
            })
          }
        </WeaRightMenu>
      </WeaDialog>
    </div>)
  }

  // 保存事件
  handleSaveAttachment = () => {
    const {
      detailAttachmentSetForm,  
    } = this.state, {
      record,
      datas=[],
      onChange,
    } = this.props;

    detailAttachmentSetForm.validateForm().then(f => {
      if(f.isValid) {
        this.setState({showAttachmentSetForm: false});

        if(datas && datas.length) {
          let index = datas.findIndex(v => v.fieldid === record.fieldid);
          if(index != -1) {
            datas[index] = {
              ...datas[index],
              attachment_settings: JSON.stringify(detailAttachmentSetForm.getFormParams())
            }
          }

          // 调用父组件中的onchange方法改变值
          if(onChange && typeof(onChange) === "function") {
            onChange(datas);
          }
        }
      }else {
        f.showErrors();
        this.setState({
          detailAttachmentSetForm: f 
        })
      }
    })
  }

  // 获取弹窗上的右键按钮
  getAttachmentBtn = () => {
    return [{
      key: 'BTN_SAVE',
      icon: <i className='icon-coms-Preservation' />,
      content: `${getLabel(826, '确定')}`,
      onClick: this.handleSaveAttachment,
    }];
  }

  // 获取弹窗上的按钮
  getButtons = () => {
    return [
      <Button 
        ecId={`${this && this.props && this.props.ecId || ''}_Button@d3vjdb@integrationWorkflowTriggerFormButtonSubmit`} 
        type='primary' 
        onClick={this.handleSaveAttachment}
      >{getLabel(826, '确定')}</Button>
    ];
  }

  // 关闭弹窗
  closeDialog = () => {
    this.setState({
      showAttachmentSetForm: false,
      detailAttachmentSetForm: new WeaForm(),
    })
  }

  // 有值的时候显示√
  hasValueFlag = () => {
    const {
      record,
      filetype,
    } = this.props;
    let attachment_settings = '',
      showFlag = false;

    try {
      attachment_settings = record.attachment_settings ? JSON.parse(record.attachment_settings) : '';
    } catch(err){}

    if(attachment_settings) {
      // 是否有值的判断，不能简单根据record.attachment_settings是否有值判断，而是需要具体到每一个form表单项是否有值
      if('1' === filetype) {
        // filetype为1时，有必填项，如果必填项值没有填写，则不能保存，则attachment_setting没有值（但是为了避免通过数据库篡改数据，还是采用下面相对严谨的方式进行判断）
        // ftp中必填项有值，即可代表有值
        if(attachment_settings.ftp_addr && attachment_settings.ftp_pwd && attachment_settings.ftp_username) {
          showFlag = true;
        }
      } else if('2' === filetype) {
        // 本地目录
        if(attachment_settings.local_dir || attachment_settings.db_field_title) {
          showFlag = true;
        }
      } else if('3' === filetype) {
        // 数据库字段必填
        if(attachment_settings.db_field_title) {
          showFlag = true;
        }
      } else if('4' === filetype) {
        // url地址
        if(attachment_settings.url_prefix || attachment_settings.db_field_title) {
          showFlag = true;
        }
      }
    }

    if(showFlag) {
      return <span style={{color: 'green', marginLeft: 5}}>√</span>;
    } 

    if(['1', '3'].includes(filetype)) {
      return <span style={this.state.requireFlag}>*</span>
    }

    return null;
  }

  // 获取附件的form表单
  getTriggerEditDetailAttachmentSetForm = (params={}) => {
    this.setState({
      detailAttachmentSetForm: new WeaForm(),
    });

    WeaTools.callApi('/api/integration/workflowtrigger/getTriggerEditDetailAttachmentSetForm', 'POST', params).then(result => {
      if(result.status == '1') {
        let form = new WeaForm();
        form.setCondition(result.condition);

        this.setState({
          detailAttachmentSetForm: form,
          showAttachmentSetForm: true,
        });
      }
    })
  }

  // 点击设置按钮，打开附件设置
  handleClickSetAttachment = () => {
    const {
      record,
      otherParams,
      filetype,
    } = this.props;
    let attachment_settings = {};

    if(record.attachment_settings) {
      try {
        attachment_settings = JSON.parse(record.attachment_settings);
      } catch(err){}
    }

    this.getTriggerEditDetailAttachmentSetForm({
      viewid: otherParams.id, 
      fieldid: record.fieldid, 
      attachment_type: filetype, 
      attachment_settings: attachment_settings.attachment_type == filetype ? record.attachment_settings : '',
    });
  }
}
