/*
 * Create:      柿子
 * CreateDate:  2022/11/21
 * Describe：   流程配置
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Checkbox, Icon, Button, message, Select, Empty, Modal } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTableinLineEditing from 'pages/common/PublicTableinLineEditing';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import iconListVisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';
import './style/index.less';

class ProcessConfiguration extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectData: {},
      loading: false,
      checked: true,
      tableData: [],
      totalWidth: 0,
      rowID: '',
      stkSubCatID: undefined,
      rowData: {},
      formData: [],
      recordData: {}, // 保存选中行数据
      configDetailsData: [],
      configColumns: [],
      configTotalWidth: 0,
      copyLoading: false,
      copyTableData: [],
      hospID: undefined,
      visible: false,
    };
    this.staticColumns = [{
      key: 1,
      title: '序号',
      dataIndex: 'seqNo',
      align: 'center',
      width: 80
    }, {
      key: 2,
      title: '库存子类',
      dataIndex: 'stkSubCatDesc',
      align: 'center',
      width: 150
    }, {
      key: 3,
      title: '供应商',
      dataIndex: 'vendorDesc',
      align: 'center',
      width: 150
    }, {
      key: 4,
      title: '医院',
      dataIndex: 'hospDesc',
      align: 'center',
      width: 150
    }, {
      key: 5,
      title: '状态',
      dataIndex: 'statusDesc',
      align: 'center',
      width: 100
    }]
  }

  componentDidMount() {
    this.getSelectData();
    this.getTableData();
  }

  getSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '17060021');
      this.setState({ selectData: res?.result || {} }, () => {
        this.getTableColumns();
        this.getConfigTableColumns();
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 获取表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'ProcessConfiguration',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      let formData = res.result?.formData || [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        });
      }
      this.setState({ formData });
    } catch (error) {
      console.log(error)
    }
  }

  // 获取表头数据
  getConfigTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'ProcessConfigurationDetail',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        const { selectData } = this.state;
        for (let i = 0; i < columns.length; i++) {
          columns[i].isRender = 'N'; // 避免重新渲染
          columns[i].autoOpenFlag = 'N';
          columns[i].popupContainer = 'N';
          columns[i].disabledDataIndex = columns[i].dataIndex === 'statusID' ? 'optoProcessConfigDetailID' : ''; // 当前状态根据行ID判断是否可操作
          columns[i].inputType = columns[i]?.linkMethod || '';
          if (columns[i]?.linkMethod === 'Select' || columns[i]?.linkMethod === 'SelectMultiple' || columns[i]?.linkMethod === 'SelectTags') {
            columns[i].detailItem = columns[i] && columns[i].linkService ? selectData[columns[i].linkService] : [];
          }
          if (columns[i]?.linkMethod === 'Input') {
            columns[i].default = Util.getValueByUrlStr(columns[i]?.linkService || '', 'default');
            columns[i].placeholder = Util.getValueByUrlStr(columns[i]?.linkService || '', 'placeholder');
          }
        }
        this.setState({
          configColumns: columns,
          configTotalWidth: res.totalWidth
        });
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取列表数据
  getTableData = async () => {
    try {
      this.setState({ loading: true });
      let { checked, stkSubCatID } = this.state;
      let data = {
        params: [{
          stkSubCatID,
          statusFlag: checked ? 'Y' : 'N',
        }]
      }
      let res = await React.$asyncPost(this, '17060022', data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || []);
      this.setState({ tableData, loading: false }, () => {
        this.handleClearData();
      });
    } catch (error) {
      this.setState({ tableData: [], loading: false }, () => {
        this.handleClearData();
      });
    }
  }

  // 操作行
  handleRowClick = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.optoProcessConfigID))) {
          this.setState({ rowID: record.optoProcessConfigID, rowData: record }, () => {
            this.getConfigurationDetails();
          });
        } else {
          this.handleClearData();
        }
      }
    }
  }

  // 清除操作数据
  handleClearData = () => {
    this.setState({ rowID: '', rowData: {}, configDetailsData: [] });
  }

  // 获取配置详情
  getConfigurationDetails = async () => {
    try {
      const { rowID, configColumns } = this.state;
      let data = {
        params: [{
          optoProcessConfigID: rowID
        }]
      }
      let res = await React.$asyncPost(this, '17060024', data);
      let configDetailsData = res?.result || [];
      this.setState({ configDetailsData }, () => {
        for (let i = 0; i < configDetailsData.length; i++) {
          this['tableEditableRef' + i] && this['tableEditableRef' + i].setTableColumns(configDetailsData[i].columns || configColumns);
          this['tableEditableRef' + i] && this['tableEditableRef' + i].setTableData(configDetailsData[i]?.detail || []);
        }
      });
    } catch (error) {
      this.setState({ configDetailsData: [] })
    }
  }

  // 选中行操作
  handleRowClassName = (record) => {
    return record.optoProcessConfigID === this.state.rowID ? 'clickRowStyle' : '';
  }

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

  // 保存
  handleSave = async values => {
    try {
      let { recordData } = this.state;
      let data = {
        params: [{
          ...values,
          optoProcessConfigID: recordData?.optoProcessConfigID || '',
        }]
      }
      let res = await React.$asyncPost(this, '17060023', data);
      message.success(res?.errorMessage || '保存成功');
      this.modalFormRef && this.modalFormRef.modifyVisible(false, 'Y');
      this.setState({ recordData: {} }, () => {
        this.getTableData();
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 新增
  handleAdd = () => {
    let { recordData } = this.state;
    this.handleModifyFormData('N');
    if (recordData && 'optoProcessConfigID' in recordData && recordData.optoProcessConfigID) {
      this.setState({ recordData: {} })
    }
    this.modalFormRef && this.modalFormRef.modifyVisible(true);
  }

  // 编辑
  handleModify = (record, e) => {
    e.stopPropagation();
    this.handleModifyFormData('Y');
    this.setState({ recordData: React.$dataConversion(record) }, () => {
      this.modalFormRef && this.modalFormRef.modifyVisible(true);
    })
  }

  // 修改表单状态
  handleModifyFormData = (disabled) => {
    let { formData } = this.state;
    if (formData && formData.length > 0) {
      for (var i = 0; i < formData.length; i++) {
        formData[i].disabled = 'N';
        if (formData[i].dataIndex === 'startDate') { // 生效日期不可修改
          formData[i].disabled = disabled;
        }
      }
      this.setState({ formData });
    }
  }

  // 仅显示生效切换
  handleCheckboxChange = e => {
    this.setState({ checked: e.target.checked }, () => {
      this.getTableData();
    })
  }

  // 添加数据
  handleConfigAdd = (index) => {
    this['tableEditableRef' + index] && this['tableEditableRef' + index].addTableData('click')
  }

  // 配置保存
  handleConfigSave = async () => {
    try {
      let { rowID, configDetailsData } = this.state;
      let detailArr = [];
      for (let i = 0; i < configDetailsData.length; i++) {
        detailArr.push({
          ...configDetailsData[i],
          detail: this['tableEditableRef' + i] && this['tableEditableRef' + i].handleSave()
        })
      }
      let data = {
        params: [{
          optoProcessConfigID: rowID,
          detailArr
        }]
      }
      let res = await React.$asyncPost(this, '17060025', data);
      message.success(res?.errorMessage || '保存成功');
      this.getConfigurationDetails();
    } catch (error) {
      console.log(error)
    }
  }

  handleModalTableQuery = async () => {
    try {
      this.setState({ copyLoading: true });
      let { hospID } = this.state;
      let data = {
        params: [{
          stkSubCatID: '',
          statusFlag: 'Y',
          hospID
        }]
      }
      let res = await React.$asyncPost(this, '17060022', data);
      let copyTableData = Util.addKeyValueToDataSource(res.result?.rows || []);
      this.setState({ copyTableData, copyLoading: false });
    } catch (error) {
      this.setState({ copyLoading: false });
    }
  }

  // 确认复制
  handleOk = async () => {
    try {
      let { hospID } = this.state;
      if (!hospID) {
        message.error('请选择需要复制的医院');
        return;
      }
      let data = {
        params: [{
          hospID
        }]
      }
      let res = await React.$asyncPost(this, '17060139', data);
      message.success(res?.errorMessage || '复制成功');
      this.modifyVisible(false);
      this.setState({ hospID: undefined, copyTableData: [] }, () => {
        this.getTableData();
      });
    } catch (error) {
      this.setState({ copyLoading: false });
    }
  }

  modifyVisible = visible => {
    this.setState({ visible });
  }

  handleHospIDChange = e => {
    this.setState({ hospID: e }, () => {
      this.handleModalTableQuery();
    })
  };

  // 上移 | 下移
  handleMove = (index, type) => {
    this['tableEditableRef' + index][type]();
  };

  render() {
    const { loading, tableData, columns, totalWidth, recordData, formData, checked, configDetailsData, stkSubCatID, selectData, rowID, copyLoading, copyTableData, hospID, visible } = this.state;
    const operationObj = {
      width: 80,
      title: '操作',
      fixed: 'right',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <span>
          <Icon type="edit" className="common-record-span-icon"></Icon>
          <span className="span" onClick={(e) => this.handleModify(record, e)}>编辑</span>
        </span>
      ),
    };

    return (
      <div className="process-configuration">
        <Row>
          <Col span={8}>
            <div style={{ paddingRight: '8px', position: 'relative', height: '100%' }}>
              <Card
                size="small"
                bordered={false}
                className="table-body-height"
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    库存子类
                  </div>
                )}
                extra={(
                  <Checkbox checked={checked} onChange={this.handleCheckboxChange}>仅显示生效</Checkbox>
                )}
              >
                <div style={{ marginBottom: 12 }}>
                  库存子类：<Select
                    allowClear
                    showSearch
                    value={stkSubCatID}
                    placeholder="请选择"
                    optionFilterProp="seachprop"
                    className="common-query-input"
                    onChange={Util.handleSelectChange.bind(this, 'stkSubCatID')}
                  >
                    {React.$SelectOptions(selectData?.stkCat || [])}
                  </Select>
                  <Button onClick={this.getTableData}>查询</Button>
                  <Button
                    // icon="plus"
                    style={{ float: 'right' }}
                    className="add-btn add-btn-nohover"
                    onClick={this.handleAdd}
                  >添加</Button>
                  <Button ghost type="primary" style={{ float: 'right', marginRight: '6px' }} onClick={() => this.modifyVisible(true)}>流程复制</Button>
                </div>
                <PublicTablePagination
                  param={{
                    loading: loading,
                    data: tableData, // 表格数据
                    x: totalWidth, // 表格的宽度
                    componentName: 'ProcessConfiguration',
                    y: store.getState().tableHeight.y + 87,
                    height: store.getState().tableHeight.y + 137 + 'px',
                    columns: columns && columns.length > 0 ? [...columns, operationObj] : [...this.staticColumns, operationObj], // 表头配置
                  }}
                  getColumns={this.getTableColumns}
                  onClickRowPublic={this.handleRowClick}
                  setRowClassNamePublic={this.handleRowClassName}
                />
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={16}>
            <Card
              size="small"
              className="pc-right-card"
              bordered={false}
              bodyStyle={{ paddingRight: '6px' }}
              title={(
                <div className="card-title-left-img">
                  <img src={iconMessages} alt="" />
                  基础配置
                </div>
              )}
              extra={(
                <Button size="small" type="primary" disabled={!rowID} onClick={this.handleConfigSave}>保存</Button>
              )}
            >
              <div style={{ height: store.getState().tableHeight.y + 182 + 'px', overflow: 'auto', paddingRight: '12px' }}>
                {configDetailsData && configDetailsData.length > 0 ? configDetailsData.map((item, index) => {
                  return (
                    <div key={index} style={{ marginBottom: '6px' }}>
                      <div className="card-title-left-icon pc-card-title">
                        <div></div>
                        {item.title}
                        <span style={{ float: 'right' }}>
                          <Button
                            size="small"
                            style={{ marginTop: '12px' }}
                            className="add-btn add-btn-nohover"
                            onClick={() => this.handleConfigAdd(index)}
                          >
                            新增
                          </Button>
                          <Button
                            ghost
                            type="primary"
                            size="small"
                            style={{ margin: '12px', marginBottom: 0 }}
                            onClick={() => this.handleMove(index, 'handleUp')}
                          >
                            上移
                          </Button>
                          <Button
                            ghost
                            type="primary"
                            size="small"
                            style={{ marginTop: '12px' }}
                            onClick={() => this.handleMove(index, 'handleDown')}
                          >
                            下移
                          </Button>
                        </span>
                      </div>
                      <div style={{ width: '100%' }}>
                        <PublicTableinLineEditing
                          admID="empty"
                          tooltipFlag="N"
                          operationFlag="Y"
                          modifyFlag="N"
                          rowSelectionFlag="Y"
                          recordID="optoProcessConfigDetailID"
                          deleteCode="17060108"
                          loading={false}
                          // maxHeight={250}
                          _key={item?.key || (index + 1)}
                          componentName="ProcessConfigurationDetail"
                          onRef={ref => this['tableEditableRef' + index] = ref}
                          getColumns={this.getConfigTableColumns}
                        />
                        {/* 初始版流程配置/已遗弃 */}
                        {/* <div className="pc-check-card" style={{ width: len.length * 120 + 2 + 'px' }}>
                        {item.detail && item.detail.map((childItem, childIndex) => {
                          return (
                            <div key={childIndex} className="pc-check-item">
                              <div className="pc-check-title ellipsis">
                                <Tooltip title={childItem.optoProcessDesc}>
                                  {childItem.optoProcessDesc}
                                </Tooltip>
                              </div>
                              <div className="pc-check-switch flex-center">
                                <Switch checkedChildren="开" unCheckedChildren="关" disabled={!(childItem?.modifyConfig === 'Y')} checked={childItem.openConfig === 'Y' ? true : false} onChange={(e) => this.handleSwithChange(e, childItem)} />
                              </div>
                            </div>
                          )
                        })}
                      </div> */}
                      </div>
                    </div>
                  )
                }) : (
                  <div style={{ height: '500px' }} className="flex-center">
                    <Empty />
                  </div>
                )}
              </div>
            </Card>
          </Col>
        </Row>
        {/* 主表新增弹窗 */}
        <PublicModalFormHooks
          idField="optoProcessConfigID"
          title="添加子类"
          rowData={recordData}
          formData={formData}
          selectData={selectData}
          onRef={ref => this.modalFormRef = ref}
          recordFormInput={this.recordFormInput}
          handleSave={this.handleSave}
        />
        <Modal
          width="1200px"
          title="复制配置到本院"
          visible={visible}
          destroyOnClose={true}
          onOk={this.handleOk}
          onCancel={() => this.modifyVisible(false)}
        >
          <div className="table-body-height">
            <div style={{ marginBottom: '12px' }}>
              医院：<Select
                allowClear
                showSearch
                value={hospID}
                placeholder="请选择"
                optionFilterProp="seachprop"
                className="common-query-input"
                style={{ width: '300px' }}
                onChange={this.handleHospIDChange}
              >
                {React.$SelectOptions(selectData?.hosp || [])}
              </Select>
              <Button type="primary" onClick={this.handleModalTableQuery}>查询</Button>
            </div>
            <PublicTablePagination
              param={{
                loading: copyLoading,
                data: copyTableData, // 表格数据
                x: totalWidth, // 表格的宽度
                y: 400,
                height: '450px',
                columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
              }}
            />
          </div>
        </Modal>
      </div>
    )
  }
};

export default ProcessConfiguration;