/*
 * Create:      柿子
 * CreateDate:  2023/11/23
 * Describe：   图标设置【公共/科室】
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Select, Input, Checkbox, message, Popconfirm } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import CommonConfigCopy from './component/CommonConfigCopy';
import iconListVisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';
import './style/index.less';

class CommonIconSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userData: React.$getSessionData(),
      queryParams: {
        alias: undefined, // 名称
        useFlag: true, // 仅显示生效
      },
      loading: false,
      columns: [],
      tableData: [],
      totalWidth: 0,
      rowID: '',
      rowData: {},
      selectData: {},
      formData: [],
      conditionData: {}, // 记录图标显示条件下拉框数据
    };
  };

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

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  };

  // 获取下拉数据
  getSelectData = async () => {
    try {
      let data = {
        params: [{}]
      }
      let res = await React.$asyncPost(this, '04011011', data);
      this.setState({ selectData: res?.result || {} }, () => {
        this.getTableData();
        this.getTableColumns();
      });
    } catch (error) {
      console.log(error);
      this.getTableData();
      this.getTableColumns();
    }
  };

  // 获取表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: this.props.locID ? 'NSLocIconSettings' : 'NSCommonIconSettings',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let formData = res.result?.formData || [];
      if (formData && formData.length > 0) {
        let displayModeDataIndex = '';
        let defaultDisabledArr = [];
        let defaultDisplayModeValue = '';
        for (let i = 0; i < formData.length; i++) {
          formData[i].defaultRequired = formData[i]?.required || 'N'; // 保留原有的设置 - 置灰时需要
          if (formData[i]?.disabled === 'Y') {
            defaultDisabledArr.push(formData[i]?.dataIndex);
          }
          if (formData[i]?.dataIndex === 'displayMode') { // 图标表达方式
            formData[i].callBackResult = 'Fn';
            formData[i].changeCallBack = this.handleDisplayModeChange;
            displayModeDataIndex = formData[i]?.className || 'displayModeArr';
            defaultDisplayModeValue = formData[i]?.default || '';
          }
        }
        this.setState({ formData, displayModeDataIndex, defaultDisabledArr }, () => {
          this.handleDisplayModeChange(defaultDisplayModeValue, 'defaultVal');
        });
      }
    } catch (error) {
      console.log(error)
    }
  };

  // 表达方式change事件
  handleDisplayModeChange = (e, type) => {
    let { selectData, displayModeDataIndex, formData, defaultDisabledArr } = this.state;
    let displayModeList = selectData && displayModeDataIndex in selectData ? selectData[displayModeDataIndex] : []; // 图标表达方式下拉数据
    if (type === 'defaultVal') {
      let currentDefaultItem = [];
      if (displayModeList && displayModeList.length > 0 && e && e.indexOf('index-') > -1) { // 默认下标
        let arrIndex = e.split('index-')[1];
        currentDefaultItem = [displayModeList[arrIndex]];
      } else { // 根据后台返回的默认标志默认
        currentDefaultItem = displayModeList.filter(item => item.default === 'Y');
      }
      e = currentDefaultItem && currentDefaultItem.length > 0 ? (currentDefaultItem[0]?.id || undefined) : undefined;
    }
    let disabledArr = Util.returnDataCccordingToAttributes(displayModeList, e)?.disabledArr || [];
    if (disabledArr && Array.isArray(disabledArr) && disabledArr.length > 0) {
      let disabledFieldsValue = {};
      for (let i = 0; i < formData.length; i++) {
        if (!(defaultDisabledArr.includes(formData[i].dataIndex))) { // 如果默认就是置灰的就不自动置成可编辑状态
          formData[i].disabled = 'N';
          formData[i].required = formData[i]?.defaultRequired || 'N';
        }
        if (disabledArr.includes(formData[i].dataIndex)) { // 将关联的字段置灰 - 并且将必填标志清空
          formData[i].disabled = 'Y';
          formData[i].required = 'N';
          disabledFieldsValue[formData[i].dataIndex] = undefined;
        }
      }
      this.setState({ formData }, () => {
        type === 'displayMode' && this.formRef?.setFieldsValue(disabledFieldsValue); // 选择数据时清楚置灰相关输入域的数据
      });
    }
  }

  // 请求列表数据
  getTableData = async (isClear) => {
    try {
      this.setState({ loading: true })
      let { queryParams } = this.state;
      let data = {
        params: [{
          ...queryParams,
          // Y - 启用; N - 查全部
          useFlag: queryParams.useFlag ? 'Y' : 'N',
          locID: this.props.locID || undefined, // 科室id
        }],
      }
      let res = await React.$asyncPost(this, this.props.locID ? '04011014' : '04011018', data); // 04011018为公共界面 | 04011014为科室管理子界面
      let tableData = Util.addKeyValueToDataSource(res?.result || [], '', 0);
      this.setState({ tableData, total: res.result?.total || tableData?.length || 0, loading: false }, () => {
        isClear !== 'N' && this.handleClear();
      });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  };

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      if (dataIndex === 'useFlag') {
        this.getTableData();
      }
    })
  };

  // 操作行
  onClickRowPublic = (record) => {
    let idIndex = this.props.locID ? 'id' : 'comIconID';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record[idIndex]))) {
          this.setState({
            rowID: record[idIndex],
            rowData: record,
          }, () => {
            record && 'displayMode' in record && record.displayMode && this.handleDisplayModeChange(record?.displayMode || ''); // 修改表单输入域状态
            this.getConditionOptions(); // 获取图标显示条件下拉框数据
          })
        } else {
          this.handleClear();
        }
      }
    }
  };

  handleClear = () => {
    this.setState({ rowID: '', rowData: {} });
  };

  // 选中行操作
  setRowClassNamePublic = (record) => {
    let idIndex = this.props.locID ? 'id' : 'comIconID';
    return record[idIndex] === this.state.rowID ? 'clickRowStyle' : '';
  };

  // 复制
  handleCopy = () => {
    this.copyRef && this.copyRef.modifyVisible(true);
  };

  handleMove = (record, direction, dataIndex, e) => {
    React.$stopPropagation(e);
    let tableData = this.state[dataIndex];
    const rowKey = record?.key;
    const currentIndex = tableData.findIndex(item => item.key === rowKey);
    if (direction === 'up' && currentIndex > 0) {
      [tableData[currentIndex - 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex - 1]];
      // 更新key值
      tableData[currentIndex].key = currentIndex;
      tableData[currentIndex - 1].key = currentIndex - 1;
    } else if (direction === 'down' && currentIndex < (tableData.length - 1)) {
      [tableData[currentIndex + 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex + 1]];
      // 更新key值
      tableData[currentIndex].key = currentIndex;
      tableData[currentIndex + 1].key = currentIndex + 1;
    }
    this.state[dataIndex] = tableData;
    this.setState({}, () => {
      dataIndex === 'tableData' && this.handleMoveSave();
    })
  };

  // 保存排序数据
  handleMoveSave = async () => {
    try {
      const { tableData } = this.state;
      let sortArr = tableData && tableData.map(item => item.id);
      let data = {
        params: [{
          sortArr
        }]
      }
      let res = await React.$asyncPost(this, '04011015', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData('N');
    } catch (error) {
      console.log(error);
    }
  };

  getOperationObj = (dataIndex) => {
    // 列表操作
    const operationObj = {
      width: 80,
      key: 'operation',
      title: '操作',
      align: 'center',
      render: (text, record, index) => this.handleRenderMoveBtn(text, record, index, dataIndex)
    };
    return operationObj;
  };

  // 渲染移动按钮
  handleRenderMoveBtn = (text, record, index, dataIndex) => {
    let tableLen = this.state[dataIndex]?.length || 0;
    return (
      <>
        <Button
          type="link"
          size="small"
          disabled={index === 0}
          style={{ marginRight: '8px' }}
          onClick={(e) => this.handleMove(record, 'up', dataIndex, e)}
        >
          上移
        </Button>
        <Button
          type="link"
          size="small"
          disabled={index >= tableLen - 1}
          onClick={(e) => this.handleMove(record, 'down', dataIndex, e)}
        >
          下移
        </Button>
      </>
    )
  };

  // 保存
  handleSave = async (isValid) => {
    try {
      const { rowData } = this.state;
      let baseInfoFormValue = await this.formRef.handleSave();
      if (baseInfoFormValue.error) {
        message.error('请完善必填信息');
        return;
      }
      let data = {
        params: [{
          ...baseInfoFormValue,
          id: rowData?.id || '',
          seqNo: rowData?.seqNo || '', // 序号
          saveType: this.props.locID ? 'W' : 'C', // 保存类型【C:公共 W:病区】
          locID: this.props.locID || undefined, // 病区ID
          comIconID: rowData?.comIconID || '', // 公共配置ID
          isValid: isValid || 'Y', // 是否生效
        }]
      }
      let res = await React.$asyncPost(this, '04011013', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  };

  // 从本科移除
  handleDelete = async () => {
    try {
      const { rowData } = this.state;
      let data = {
        params: [{
          ...rowData
        }]
      }
      let res = await React.$asyncPost(this, '04011017', data);
      message.success(res?.errorMessage || '删除成功');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  };

  // 复制数据时判断是否存在
  handleDuplicateCheck = (checkArr) => {
    const { tableData } = this.state;
    let repeatArr = [];
    if (Array.isArray(checkArr) && checkArr.length > 0) {
      const tableDataIds = tableData.map(item => item.comConfigID);
      for (let i = 0; i < checkArr.length; i++) {
        if (tableDataIds.includes(checkArr[i].comConfigID)) {
          repeatArr.push(checkArr[i]?.descripts || checkArr[i].comConfigID);
        }
      }
    }
    return repeatArr;
  };

  // 获取图标显示条件下拉数据
  getConditionOptions = async () => {
    try {
      let { rowData, selectData, conditionData } = this.state;
      let comIconID = rowData?.comIconID || '';
      let currentConditionArr = [];
      if (conditionData && comIconID && conditionData['conditionArr' + comIconID]) {
        currentConditionArr = conditionData['conditionArr' + comIconID];
      } else {
        let data = {
          params: [{
            comIconID
          }]
        }
        let res = await React.$asyncPost(this, '04011012', data);
        currentConditionArr = res?.result || [];
        conditionData['conditionArr' + comIconID] = res?.result || [];
      }
      this.setState({ selectData: { ...selectData, conditionArr: currentConditionArr } });
    } catch (error) {
      console.log(error)
    }
  };

  render() {
    const { tabHeight } = this.props;
    const { queryParams, loading, columns, tableData, totalWidth, rowID, rowData, selectData, formData
    } = this.state;

    return (
      <div className="common-icon-settings">
        <Row>
          <Col span={10}>
            <div
              style={{ paddingRight: '8px', position: 'relative', height: '100%' }}
            >
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    图标列表
                  </div>
                )}
                extra={(
                  <Checkbox checked={queryParams?.useFlag || false} onChange={(e) => this.handleModifyInputValue(e.target.checked, 'useFlag')}>仅显示生效</Checkbox>
                )}
              >
                <div className="table-body-height">
                  <div style={{ marginBottom: 12 }}>
                    <span className="common-input-label">名称：</span>
                    <Input
                      title="输入内容后可回车检索"
                      placeholder="请输入名称检索"
                      className="common-query-input"
                      value={queryParams?.alias}
                      onChange={(e) => this.handleModifyInputValue(e.target.value, 'alias')}
                      onPressEnter={this.getTableData}
                    />
                    <span className="common-input-label">显示位置：</span>
                    <Select
                      placeholder="请选择"
                      className="common-query-input"
                      style={{ width: '120px' }}
                      value={queryParams?.filterPos}
                      onChange={(e) => this.handleModifyInputValue(e, 'filterPos')}
                    >
                      {React.$SelectOptions(selectData?.positionArr || [])}
                    </Select>
                    <Button type="primary" style={{ marginRight: 12 }} onClick={this.getTableData}>查询</Button>
                    {this.props.locID && <Button ghost type="primary" style={{ float: 'right' }} onClick={this.handleCopy}>复制</Button>}
                  </div>
                  <PublicTablePagination
                    param={{
                      loading,
                      data: tableData, // 表格数据
                      x: totalWidth, // 表格的宽度
                      y: tabHeight ? tabHeight : store.getState().tableHeight.y + 86,
                      height: tabHeight ? (tabHeight + 50 + 'px') : store.getState().tableHeight.y + 136 + 'px',
                      componentName: this.props.locID ? 'NSLocIconSettings' : 'NSCommonIconSettings',
                      columns: columns && columns.length > 0 ? [...columns, this.getOperationObj('tableData')] : [], // 表头配置
                    }}
                    getColumns={this.getTableColumns}
                    onClickRowPublic={this.onClickRowPublic}
                    setRowClassNamePublic={this.setRowClassNamePublic}
                  />
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={14}>
            <Card
              bordered={false}
              size="small"
              title={(
                <div className="card-title-left-img">
                  <img src={iconMessages} alt="" />
                  图标设置
                </div>
              )}
              extra={(
                this.props.locID && rowID && <Button size="small" type="danger" onClick={() => this.handleSave('N')}>从本科移除</Button>
              )}
            >
              <div
                style={{
                  height: (tabHeight ? (tabHeight + 92) : store.getState().tableHeight.y + 180) + 'px',
                  overflow: 'auto',
                  padding: '12px'
                }}
                className="scroll-bar-style"
              >
                <DynamicRenderingForm
                  rowData={rowData}
                  selectData={selectData}
                  formData={formData}
                  onRef={ref => this.formRef = ref}
                />
                <Row style={{ marginTop: '12px' }}>
                  <Col span={4} className="ant-form-item-label"></Col>
                  <Col span={18}>
                    <Button style={{ marginRight: '12px' }} type="primary" disabled={!rowID} onClick={() => this.handleSave('Y')}>{this.props.locID ? '保存到本科' : '保存'}</Button>
                    {this.props.locID ? (
                      <Popconfirm
                        title="确认恢复默认设置吗?"
                        disabled={!(rowData?.deleteFlag === 'Y')}
                        onConfirm={this.handleDelete}
                      >
                        <Button disabled={!(rowData?.deleteFlag === 'Y')}>恢复默认设置</Button>
                      </Popconfirm>
                    ) : (
                      <Popconfirm
                        title="删除不可恢复，你确定要删除吗?"
                        disabled={!rowID}
                        onConfirm={() => this.handleSave('N')}
                      >
                        <Button type="danger" disabled={!rowID}>删除</Button>
                      </Popconfirm>
                    )}
                  </Col>
                </Row>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 复制配置 */}
        <CommonConfigCopy
          queryCode="04011014"
          copyCode="04011016"
          componentName="CopyCommonIconConfig"
          locID={this.props.locID || undefined}
          selectData={selectData}
          onRef={ref => this.copyRef = ref}
          handleQuery={this.getTableData}
          duplicateCheck={this.handleDuplicateCheck}
        />
      </div>
    )
  }
};

export default CommonIconSettings;