/*
 * Create:      柿子
 * CreateDate:  2023/12/22
 * Describe：   系统主题配置
 * */
import React, { Component } from 'react';
import { Card, Row, Col, Radio, Button, message, Icon, Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import './style/index.less';
import Login from 'pages/login/Login';

const { Meta } = Card;

class SystemThemeConfiguration extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectData: {},
      formData: [],
      themeData: [],
      themeID: '',
      themeItemData: {},
      modalFormData: [],
      modalRowData: {}
    }
  };

  componentDidMount() {
    this.getColumnsData();
    this.getThemeData();
    this.getModalFormData();
  };

  getColumnsData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SystemThemeConfiguration',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      this.setState({ columns, formData: res?.result?.formData || [] });
    } catch (error) {
      console.log(error)
    }
  };

  getModalFormData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SystemThemeConfigurationModal',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      this.setState({ modalFormData: res?.result?.formData || [] });
    } catch (error) {
      console.log(error)
    }
  };

  getThemeData = async () => {
    try {
      let res = await React.$asyncPost(this, '01040312');
      let themeData = res.result?.rows || [];
      // 默认选择自定义主题
      for (let i = 0; i < themeData.length; i++) {
        if (themeData[i].inUseFlag === 'Y') {
          this.handleTemplateChange(themeData[i]);
          break;
        }
      }
      this.setState({ themeData });
    } catch (error) {
      console.log('error', error)
    }
  };

  handleTemplateChange = (item) => {
    let themeDetail = item?.themeDetail || [];
    let rowData = {};
    for (let i = 0; i < themeDetail.length; i++) {
      let themeItemCode = themeDetail[i]?.themeItemCode || '';
      let themeItemValue = themeDetail[i]?.themeItemValue || undefined;
      rowData[themeItemCode] = React.$isJsonString(themeItemValue) ? JSON.parse(themeItemValue) : themeItemValue;
    }
    this.setState({ themeID: item?.themeID || '', themeItemData: { ...item, ...rowData } });
  };

  handleSave = async (collBack) => {
    try {
      const { themeID } = this.state;
      let values = await this.formRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息');
        return;
      }
      let themeDetail = [];
      for (let keys in values) {
        if (keys !== 'error') {
          let inputVal = values[keys];
          themeDetail.push({ themeItemCode: keys, themeItemValue: inputVal && Array.isArray(inputVal) && inputVal.length > 0 ? JSON.stringify(inputVal) : inputVal });
        }
      }
      let data = {
        params: [{
          themeID,
          themeDetail
        }]
      }
      let res = await React.$asyncPost(this, '01040314', data);
      this.getThemeData();
      if (collBack) {
        collBack();
      } else {
        message.success(res?.errorMessage || '保存成功');
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 重置
  handleReset = () => {
    const { themeItemData } = this.state;
    let rowData = {};
    let themeDetail = themeItemData?.themeDetail || [];
    for (let i = 0; i < themeDetail.length; i++) {
      let themeItemCode = themeDetail[i]?.themeItemCode || '';
      rowData[themeItemCode] = undefined;
    };
    this.setState({ themeItemData: { ...themeItemData, ...rowData } });
    this.formRef?.resetFields();
  };

  // 添加
  handleAdd = () => {
    const { modalRowData } = this.state;
    if (modalRowData && 'themeID' in modalRowData && modalRowData.themeID) {
      this.setState({ modalRowData: {} })
    }
    this.modalRef && this.modalRef.modifyVisible(true);
  }

  // 编辑
  handleCompile = (record) => {
    if (record?.themeTypeCode === 'S') {
      message.info('系统默认主题，不支持修改！')
      return;
    }
    this.setState({ modalRowData: record }, () => {
      this.modalRef && this.modalRef.modifyVisible(true);
    })
  }

  // 记录表单的值
  recordMainFormInput = record => {
    this.setState({ modalRowData: { ...this.state.modalRowData, ...record } })
  };

  handleModalSave = async (values) => {
    try {
      const { modalRowData } = this.state;
      let data = {
        params: [{
          ...values,
          themeID: modalRowData?.themeID || ''
        }]
      }
      let res = await React.$asyncPost(this, '01040313', data);
      message.success(res?.errorMessage || '保存成功');
      this.getThemeData();
      this.modalRef && this.modalRef.modifyVisible(false, 'Y');
    } catch (error) {
      console.log(error);
    }
  };

  // 应用
  handleApplication = async () => {
    try {
      const { themeID } = this.state;
      if (!themeID) {
        message.error('请选择需要引用的主题');
        return;
      }
      let data = {
        params: [{
          themeID
        }]
      }
      let res = await React.$asyncPost(this, '01040315', data);
      message.success(res?.errorMessage || '应用成功');
    } catch (error) {
      console.log(error);
    }
  };

  // 预览
  handlePreview = () => {
    const { themeItemData } = this.state;
    let rowData = {};
    let themeDetailCode = (themeItemData?.themeDetail || []).map(item => item?.themeItemCode || '');
    let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
    // 判断是否是本地，如果是本地的话取https配置地址，线上则取地址栏地址 （内外网）
    let url = windowHost && (windowHost.indexOf('localhost') !== -1 || windowHost.indexOf('127.0.0.1') !== -1) ? $http.ipDeault : windowHost;
    for (let keys in themeItemData) {
      if (themeDetailCode.indexOf(keys) > -1) {
        let values = themeItemData[keys];
        rowData[keys] = values && Array.isArray(values) && values.length > 0 ? url + '/images/optomefile/' + values[0]?.filePath : values;
      }
    }
    this.loginRef && this.loginRef.handleSwitchThemes(rowData);
  };

  render() {
    const { selectData, formData, themeData, themeID, modalFormData, modalRowData, themeItemData } = this.state;
    return (
      <div className="system-theme-configuration">
        <Row style={{ padding: '12px', height: '100%' }}>
          <Col style={{ height: '100%', paddingRight: '6px' }} span={10}>
            <div style={{ height: '100%', overflow: 'auto' }} className="scroll-bar-style">
              <h3 style={{ lineHeight: '46px' }}>系统主题方案配置</h3>
              <p style={{ color: '#999', fontWeight: 'normal' }}>选择配色方案来设置系统外观</p>
              <div style={{ marginBottom: '12px' }} className="flex-wrap-align-items">
                {themeData && themeData.map((item, index) => {
                  return (
                    <div
                      key={index}
                      style={{ marginRight: '12px', marginBottom: '12px' }}
                      className={item?.inUseFlag === 'Y' ? 'stc-current-theme' : ''}
                      onClick={() => this.handleTemplateChange(item)}
                      onDoubleClick={() => this.handleCompile(item)}
                    >
                      <Card bodyStyle={{ padding: '12px' }} style={{ width: '200px' }}>
                        <div className="flex">
                          <Radio checked={themeID === item.themeID}></Radio>
                          <Meta
                            title={(
                              <span
                                title={item?.themeDesc || ''}
                                style={{ display: 'inline-block', width: '150px', paddingTop: '4px' }}
                                className="ellipsis"
                              >
                                {item?.themeDesc || ''}
                              </span>
                            )}
                            description={(
                              <span
                                title={item?.themeENDesc || ''}
                                style={{ display: 'inline-block', width: '150px', fontWeight: 'normal' }}
                                className="ellipsis"
                              >
                                {item?.themeENDesc || ''}
                              </span>
                            )}
                          />
                        </div>
                      </Card>
                    </div>
                  )
                })}
                <div style={{ marginRight: '12px', marginBottom: '12px' }}>
                  <Card bodyStyle={{ padding: '0' }} style={{ width: '200px' }} onClick={this.handleAdd}>
                    <div style={{ height: '84px', cursor: 'pointer' }} className="flex-center">
                      <Icon style={{ fontSize: '24px' }} type="plus" />
                    </div>
                  </Card>
                </div>
              </div>
              <DynamicRenderingForm
                rowData={themeItemData}
                selectData={selectData}
                formData={formData}
                onRef={ref => this.formRef = ref}
              />
              <Row style={{ marginTop: '8px' }}>
                <Col span={4}></Col>
                <Col span={20}>
                  <Button style={{ marginRight: '12px' }} ghost type="primary" onClick={this.handlePreview}>预览</Button>
                  <Popconfirm title={'确认应用【' + (themeItemData?.themeDesc || '当前主题') + '】吗?'} disabled={themeItemData?.inUseFlag === 'Y'} onConfirm={() => this.handleSave(this.handleApplication)}>
                    <Button type="primary" disabled={themeItemData?.inUseFlag === 'Y'}>应用</Button>
                  </Popconfirm>
                  <Button style={{ margin: '0 12px' }} type="primary" disabled={themeItemData?.themeTypeCode === 'S'} onClick={() => this.handleSave('')}>保存</Button>
                  <Button disabled={themeItemData?.themeTypeCode === 'S'} onClick={this.handleReset}>重置</Button>
                </Col>
              </Row>
            </div>
          </Col>
          <Col span={14} style={{ height: '100%', padding: '20px 0' }}>
            <div className="stc-preview" style={{ width: '100%', height: '100%' }}>
              <Login
                interfaceType="preview"
                onRef={ref => this.loginRef = ref}
              />
            </div>
          </Col>
        </Row>

        {/* 添加主题 */}
        <PublicModalFormHooks
          onRef={ref => this.modalRef = ref}
          formData={modalFormData}
          rowData={modalRowData}
          recordFormInput={this.recordMainFormInput}
          handleSave={this.handleModalSave}
        />
      </div>
    )
  }
};

export default SystemThemeConfiguration;