// 移动护理表单设置
import React, { Component } from 'react';
import { Card, Row, Col, Input, Select, Button, Table, Icon, Divider, Popconfirm, Checkbox, Form, Switch, message, Pagination } from 'antd';
import store from 'store';
import '../../workstation/style/index.less'; // 医嘱录入小图标
import './style/index.less';
import CommonPagination from 'components/pagination/index';
import AddCareForm from './component/AddCareForm';
import { $http } from 'containers/config/https';
import { Util } from 'tools';

let { Option } = Select;
const { Search } = Input;

const EditableContext = React.createContext();

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === 'select') {
      return <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '80%' }}>
        {this.props.option}
      </Select>;
    } else if (this.props.inputType === 'input-number') {
      return <Input style={{ width: '80%' }} type="number" className="input-number" />;
    } else if (this.props.inputType === 'checkout') {
      return <Checkbox />;
    } else if (this.props.inputType === 'switch') {
      return <Switch />;
    } else {
      return <Input style={{ width: '80%' }} />;
    }

  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      isRequired,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (inputType === 'switch' ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: isRequired,
                  message: `${title + (JSON.parse(window.sessionStorage.userData).language == 'EN' ? ' Can not be empty!' : '不能为空!')}`,
                },
              ],
              valuePropName: 'checked',
              initialValue: record[dataIndex] === 'Y' ? true : false,
            })(this.getInput())}
          </Form.Item>
        ) : (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: isRequired,
                  message: `${title + (JSON.parse(window.sessionStorage.userData).language == 'EN' ? ' Can not be empty!' : '不能为空!')}`,
                },
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        )) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

class MobileCareFormSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formUsage: undefined, // 按科室查询下拉
      formName: undefined, // 表单名称
      isEffective: true, // 仅显示生效
      assessmentRowId: "", // 评估表选中行ID
      assessmentRowData: {}, // 评估表选中行数据
      assessmentTableData: [], // 表单设置列表数据
      locDesc: undefined, // 科室名称
      locType: undefined, // 科室类型
      locTableData: [], // 科室表格数据
      assessmentTemplateTableData: [], // 评估模板列表
      elementRangeTableData: [], // 元素值域列表数据
      elementRangeTotal: 0,
      editingKey: "",
      elementRangeEditingKey: "",
      assessmentTemplateSelectedRowKeys: [],
      assessmentTemplateSelectedRows: [],
      elementRangeSelectedRowKeys: [],
      elementRangeSelectedRows: [],
      assessmentPage: 1,
      assessmentTotal: 0,
      loading: false,
      assessmentPageSize: 10,
      locPage: 1,
      locTotal: 0,
      locPageSize: 10,
      parameterSetting: {}, // 初始化数据
      assessmentTemplateRowId: "", // 评估表行ID
      assessmentTemplateRowData: {}, // 评估表行数据
      locSelectedRowKeys: [],
      locSelectedRows: []
    };

    // 评估表表头数据
    this.assessmentColumns = [
      { title: '显示顺序', dataIndex: 'templateSeqNo', key: '1', width: '80px', align: "center" },
      { title: '代码', dataIndex: 'templateCode', key: '2', width: '140px', align: "center" },
      { title: '名称', dataIndex: 'templateDesc', key: '3', width: '200px', align: "center" },
      {
        title: '状态',
        dataIndex: 'templateStatus',
        key: '4',
        width: '80px',
        align: "center",
        render(templateStatus) {
          let config = {
            'Y': <span style={{ color: 'rgba(0, 0, 0, 0.65)', marginLeft: '-10px' }}>有效</span>,
            'N': <span style={{ color: '#FF0066', marginLeft: '-10px' }}>无效</span>
          }
          return config[templateStatus];
        }
      },
      {
        title: '操作',
        key: 5,
        align: "center",
        fixed: 'right',
        width: 100,
        render: (text, record) => (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={(e) => this.handleCompile(e, record)}>编辑</span>
          </span>
        ),
      }
    ];

    // 生活自理能力评估模板
    this.assessmentTemplateColumns = [
      { title: '元素描述', dataIndex: 'tempElementDesc', key: '1', width: '150px', align: "center", inputType: 'input', editable: true, isRequired: true },
      {
        title: '元素格式', dataIndex: 'tempEleTypeID', key: '2', isRequired: true,
        width: '150px', align: "center", inputType: 'select', editable: true,
        render: (text, record) => {
          return <span>{record.tempEleTypeDesc}</span>
        }
      },
      {
        title: '是否必填', dataIndex: 'tempEleIsRequired', key: '3',
        width: '80px', align: "center", inputType: 'switch', editable: true,
        render(tempEleIsRequired) {
          let config = {
            'Y': <span style={{ color: 'rgba(0, 0, 0, 0.65)', marginLeft: '-10px' }}>是</span>,
            'N': <span style={{ color: 'rgba(0, 0, 0, 0.65)', marginLeft: '-10px' }}>否</span>
          }
          return config[tempEleIsRequired];
        }
      },
      {
        title: '序号（列表显示）',
        dataIndex: 'tempEleTableSeqNo',
        key: '4',
        width: '150px',
        align: "center",
        inputType: 'input-number',
        editable: true,
      },
      {
        title: '显示在列表', dataIndex: 'tempEleTableItem', key: '5',
        width: '100px', align: "center", inputType: 'switch', editable: true,
        render(tempEleTableItem) {
          let config = {
            'Y': <span style={{ color: 'rgba(0, 0, 0, 0.65)', marginLeft: '-10px' }}>是</span>,
            'N': <span style={{ color: 'rgba(0, 0, 0, 0.65)', marginLeft: '-10px' }}>否</span>
          }
          return config[tempEleTableItem];
        }
      },
      { title: '列宽', dataIndex: 'tempEleTableWidth', key: '6', width: '80px', align: "center", inputType: 'input-number', editable: true, },
      {
        title: '操作',
        key: '7',
        align: "center",
        fixed: 'right',
        width: 130,
        render: (text, record) => {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <span
                    className='span'
                    onClick={() => this.handleAssessmentTemplateSave(form)}
                    style={{ color: '#108EE9' }}
                  >
                    保存
                  </span>
                )}
              </EditableContext.Consumer>
              <Divider type="vertical" />
              <Popconfirm title="确认可能会造成数据丢失，是否确认???" onConfirm={() => this.handleCancel(record)}>
                <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                <span style={{ color: 'rgba(240,65,52,1)' }} className='span'>取消</span>
              </Popconfirm>
            </span>
          ) : (
            <EditableContext.Consumer>
              {form => (
                <span disabled={editingKey !== ''} onClick={() => this.handleEdit(form, record.key)}>
                  <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                  <span className='span'>编辑</span>
                </span>
              )}
            </EditableContext.Consumer>
          );
        },
      }
    ];

    // 设置元素值域
    this.elementRangeColumns = [
      { title: '代码', dataIndex: 'tempEleDataCode', key: '1', width: 150, align: "center", inputType: 'input', editable: true },
      { title: '描述', dataIndex: 'tempEleDataDesc', key: '2', width: 150, align: "center", inputType: 'input', editable: true },
      { title: '元素值', dataIndex: 'tempEleDataValue', key: '3', width: 150, align: "center", inputType: 'input', editable: true },
      {
        title: '是否设为默认值', dataIndex: 'tempEleDataDefault', key: '4',
        width: 100, align: "center", inputType: 'switch', editable: true,
        render(tempEleDataDefault) {
          let config = {
            'Y': <span style={{ color: 'rgba(0, 0, 0, 0.65)', marginLeft: '-10px' }}>是</span>,
            'N': <span style={{ color: 'rgba(0, 0, 0, 0.65)', marginLeft: '-10px' }}>否</span>
          }
          return config[tempEleDataDefault];
        }
      },
      {
        title: '操作',
        key: '5',
        align: "center",
        width: 130,
        render: (text, record, index) => {
          const { elementRangeEditingKey } = this.state;
          const editable = this.isEditing(record, "elementRange");
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <span
                    className='span'
                    onClick={() => this.handleElementRangeSave(form, record)}
                    style={{ color: '#108EE9' }}
                  >
                    保存
                  </span>
                )}
              </EditableContext.Consumer>
              <Divider type="vertical" />
              <Popconfirm title="确认可能会造成数据丢失，是否确认???" onConfirm={() => this.handleCancel(record, "elementRange",)}>
                <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                <span style={{ color: 'rgba(240,65,52,1)' }} className='span'>取消</span>
              </Popconfirm>
            </span>
          ) : (
            <EditableContext.Consumer>
              {form => (
                <span disabled={elementRangeEditingKey !== ''} onClick={() => this.handleEdit(form, record.key, "elementRange")}>
                  <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                  <span className='span'>编辑</span>
                </span>
              )}
            </EditableContext.Consumer>
          );
        },
      }
    ];

    // 科室列表表头数据
    this.locColumns = [
      { title: '科室代码', dataIndex: 'tempLocConfigLocCode', key: '1', width: '100px', align: "center" },
      { title: '科室名称', dataIndex: 'tempLocConfigLocDesc', key: '2', width: '200px', align: "center" },
    ];
  }

  componentDidMount() {
    this.getParameterSetting();
    this.getAssessmentTableData();
  }

  // 3.2.1.6.10.取发药 参数设置
  getParameterSetting = () => {
    let data = {
      params: [{}]
    }
    $http.post('urlS', this, {
      code: "04220005",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ parameterSetting: res.result })
        } else {
          this.setState({ parameterSetting: {} })
        }
      }
    })
  }

  onRef = ref => {
    this.addCareFormRef = ref;
  }

  // 获取移动表单设置列表数据
  getAssessmentTableData = () => {
    let { formUsage, formName, isEffective, assessmentPage, assessmentPageSize } = this.state;
    let data = {
      params: [{
        templateLocID: formUsage,
        searchWords: formName,
        status: isEffective ? "Y" : "N"
      }],
      pagination: [{
        pageSize: assessmentPageSize,
        currentPage: assessmentPage
      }]
    }
    $http.post('urlS', this, {
      code: "04220006",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let assessmentTableData = res.result && res.result.data && res.result.data.length > 0 ? res.result.data : [];
          for (var i = 0; i < assessmentTableData.length; i++) {
            assessmentTableData[i].key = i + 1;
          }
          this.setState({
            assessmentTableData, assessmentTotal: res.result.TotalCount, assessmentRowId: "", assessmentRowData: {},
            assessmentTemplateTableData: [],
            assessmentTemplateRowId: "", assessmentTemplateRowData: {}, elementRangeTableData: [], elementRangeTotal: 0,
            editingKey: "", elementRangeEditingKey: "", assessmentTemplateSelectedRowKeys: [], assessmentTemplateSelectedRows: [],
            elementRangeSelectedRowKeys: [], elementRangeSelectedRows: []
          })
        } else {
          this.setState({
            assessmentTableData: [], assessmentTotal: 0, assessmentRowId: "", assessmentRowData: {},
            assessmentTemplateTableData: [],
            assessmentTemplateRowId: "", assessmentTemplateRowData: {}, elementRangeTableData: [], elementRangeTotal: 0,
            editingKey: "", elementRangeEditingKey: "", assessmentTemplateSelectedRowKeys: [], assessmentTemplateSelectedRows: [],
            elementRangeSelectedRowKeys: [], elementRangeSelectedRows: []
          })
        }
      }
    })
  }

  // 添加评估表
  handleAddEvaluationForm = () => {
    this.addCareFormRef.showModal();
  }

  // 编辑
  handleCompile = (e, record) => {
    e.stopPropagation()
    this.addCareFormRef.showModal(record);
  }

  // 按科室查询使用情况
  handleFormUsageChange = e => {
    this.setState({ formUsage: e }, () => {
      this.getAssessmentTableData();
    })
  }

  // 表单名称
  handleFormNameChange = e => {
    this.setState({ formName: e.target.value })
  }

  // 仅显示生效
  handleIsEffectiveChange = e => {
    this.setState({
      isEffective: e.target.checked,
    }, () => {
      this.getAssessmentTableData();
    });
  }

  // 获取评估表列表数据
  getAssessmentTemplateTableData = (searchWords) => {
    let { assessmentRowId } = this.state;
    let data = {
      params: [{
        templateID: assessmentRowId,
        searchWords: searchWords ? searchWords : ""
      }],
    }
    $http.post('urlS', this, {
      code: "04220008",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let assessmentTemplateTableData = res.result && res.result.data && res.result.data.length > 0 ? res.result.data : [];
          for (var i = 0; i < assessmentTemplateTableData.length; i++) {
            assessmentTemplateTableData[i].key = i;
          }
          this.setState({
            assessmentTemplateTableData, assessmentTotal: res.result.TotalCount,
            assessmentTemplateRowId: "", assessmentTemplateRowData: {}, elementRangeTableData: [], elementRangeTotal: 0,
            editingKey: "", elementRangeEditingKey: "", assessmentTemplateSelectedRowKeys: [], assessmentTemplateSelectedRows: [],
            elementRangeSelectedRowKeys: [], elementRangeSelectedRows: []
          })
        } else {
          this.setState({
            assessmentTemplateTableData: [], assessmentTotal: 0, assessmentTemplateRowId: "",
            assessmentTemplateRowData: {}, elementRangeTableData: [], elementRangeTotal: 0, assessmentTemplateSelectedRowKeys: [], assessmentTemplateSelectedRows: [],
            elementRangeSelectedRowKeys: [], elementRangeSelectedRows: [],
          })
        }
      }
    })
  }

  // 评估表行操作
  handleAssessmentClickRow = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.assessmentRowId === '') {
          // 保存行数据以及ID
          this.setState({ assessmentRowId: record.templateID, assessmentRowData: record }, () => {
            this.getAssessmentTemplateTableData();
            this.handleQueryLocTable(); // 查询授权所需要的的科室列表
          })
        } else {
          if (this.state.assessmentRowId !== record.templateID) {
            this.setState({ assessmentRowId: record.templateID, assessmentRowData: record }, () => {
              this.getAssessmentTemplateTableData();
              this.handleQueryLocTable(); // 查询授权所需要的的科室列表
            })
          }
        }
      }
    }
  }

  // 评估表选择行class
  setAssessmentRowClassName = (record) => {
    return record.templateID === this.state.assessmentRowId ? 'clickRowStyle' : '';
  }

  isEditing = (record, type) => {
    if (type === "elementRange") {
      return record.key === this.state.elementRangeEditingKey;
    } else {
      return record.key === this.state.editingKey;
    }
  }

  // 编辑
  handleEdit = (form, key, type) => {
    if (this.state.editingKey) {
      console.log("form", form)
    }
    if (type === "elementRange") {
      this.setState({ elementRangeEditingKey: key });
    } else {
      this.setState({ editingKey: key });
    }
  }

  // 评估模板table保存
  handleAssessmentTemplateSave = (form) => {
    // console.log(form)
    let { assessmentTemplateRowData, assessmentRowId } = this.state;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      let data = {
        params: []
      }
      let obj = JSON.parse(JSON.stringify(row));
      obj.templateID = assessmentRowId;
      obj.tempElementID = assessmentTemplateRowData && assessmentTemplateRowData.tempElementID ? assessmentTemplateRowData.tempElementID : "";
      obj.tempEleIsRequired = obj && obj.tempEleIsRequired ? "Y" : "N";
      obj.tempEleTableItem = obj && obj.tempEleTableItem ? "Y" : "N";
      data.params.push(Util.disposeData(obj));
      $http.post('urlADS', this, {
        code: "04220010",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            // 提示
            message.success(res.errorMessage);
            this.getAssessmentTemplateTableData();
          }
        }
      })
      // const newData = [...this.state.assessmentTemplateTableData];
      // const index = newData.findIndex(item => key === item.key);
      // row.tempEleIsRequired = row.tempEleIsRequired ? "Y" : "N";
      // row.tempEleTableItem = row.tempEleTableItem ? "Y" : "N";
      // if (index > -1) {
      //   const item = newData[index];
      //   newData.splice(index, 1, {
      //     ...item,
      //     ...row,
      //   });
      //   this.setState({ assessmentTemplateTableData: newData, editingKey: '' });
      // } else {
      //   newData.push(row);
      //   this.setState({ assessmentTemplateTableData: newData, editingKey: '' });
      // }
    });
  }

  // 取消
  handleCancel = (record, type) => {
    console.log(record)
    if (type === "elementRange") {
      if (record && record.tempEleDataID) {
        this.setState({ elementRangeEditingKey: '' });
      } else { // 如果未保存过的取消则直接删除
        let elementRangeTableData = JSON.parse(JSON.stringify(this.state.elementRangeTableData));
        this.setState({ elementRangeEditingKey: '', elementRangeTableData: elementRangeTableData.filter(item => item.key !== record.key) });
      }
    } else {
      if (record && record.tempElementID) {
        this.setState({ editingKey: '' });
      } else { // 如果未保存过的取消则直接删除
        let assessmentTemplateTableData = JSON.parse(JSON.stringify(this.state.assessmentTemplateTableData));
        this.setState({ editingKey: '', assessmentTemplateTableData: assessmentTemplateTableData.filter(item => item.key !== record.key) });
      }
    }
  };

  // 评估表行操作
  handleAssessmentTemplateOnRow = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.assessmentTemplateRowId === '') {
          // 保存行数据以及ID
          this.setState({ assessmentTemplateRowId: record.tempElementID, assessmentTemplateRowData: record }, () => {
            this.getElementRangeTableData()
          })
        } else {
          if (this.state.assessmentTemplateRowId !== record.tempElementID) {
            this.setState({ assessmentTemplateRowId: record.tempElementID, assessmentTemplateRowData: record }, () => {
              this.getElementRangeTableData()
            })
          }
        }
      },
      onDoubleClick: () => {
        this.props.form.resetFields();
        this.setState({ editingKey: record.key });
      }
    }
  }

  // 评估表行操作
  setAssessmentTemplateRowClassName = (record) => {
    return record.tempElementID === this.state.assessmentTemplateRowId ? 'clickRowStyle' : '';
  }

  // 元素值域行操作
  handleElementRangeOnRow = (record) => {
    return {
      onDoubleClick: () => {
        this.props.form.resetFields();
        this.setState({ elementRangeEditingKey: record.key });
      }
    }
  }

  // 获取元素值域列表数据
  getElementRangeTableData = () => {
    let { assessmentTemplateRowId } = this.state;
    if (!assessmentTemplateRowId) {
      this.setState({ elementRangeTableData: [], elementRangeTotal: 0 })
      return;
    };
    let data = {
      params: [{
        tempElementID: assessmentTemplateRowId
      }],
    }
    $http.post('urlS', this, {
      code: "04220009",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let elementRangeTableData = res.result && res.result.data && res.result.data.length > 0 ? res.result.data : [];
          for (var i = 0; i < elementRangeTableData.length; i++) {
            elementRangeTableData[i].key = i;
          }
          this.setState({ elementRangeEditingKey: '', elementRangeTableData, elementRangeTotal: res.result.TotalCount, elementRangeSelectedRowKeys: [], elementRangeSelectedRows: [] })
        } else {
          this.setState({ elementRangeEditingKey: '', elementRangeTableData: [], elementRangeTotal: 0, elementRangeSelectedRowKeys: [], elementRangeSelectedRows: [] })
        }
      }
    })
  }

  // 保存元素值域行数据
  handleElementRangeSave = (form, record) => {
    let key = this.state.elementRangeEditingKey;
    let { assessmentTemplateRowData } = this.state;
    let that = this;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      let data = {
        params: []
      }
      let obj = JSON.parse(JSON.stringify(row));;
      obj.tempElementID = assessmentTemplateRowData && assessmentTemplateRowData.tempElementID ? assessmentTemplateRowData.tempElementID : "";
      obj.tempEleDataDefault = obj && obj.tempEleDataDefault ? "Y" : "N";
      for (var k in record) {
        if (!obj[k]) {
          obj[k] = record[k]; //将行上其他数据赋值
        }
      }
      obj.tempEleDataSeqNo = record.key;
      data.params.push(Util.disposeData(obj));
      console.log("data", data)
      $http.post('urlADS', this, {
        code: "04220011",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            // 提示
            message.success(res.errorMessage);
            that.getElementRangeTableData()
          }
        }
      })

      // const newData = [...this.state.elementRangeTableData];
      // const index = newData.findIndex(item => key === item.key);
      // row.tempEleDataDefault = row.tempEleDataDefault ? "Y" : "N";
      // if (index > -1) {
      //   const item = newData[index];
      //   newData.splice(index, 1, {
      //     ...item,
      //     ...row,
      //   });
      //   this.setState({ elementRangeTableData: newData, elementRangeEditingKey: '' });
      // } else {
      //   newData.push(row);
      //   this.setState({ elementRangeTableData: newData, elementRangeEditingKey: '' });
      // }
    });
  }
  /**
   * 调用后台保存元素值域
   */
  elementRangeSave = () => {

  }


  // 处理表头数据
  processingHeaderData = (columns, type) => {
    let { parameterSetting } = this.state;
    let elementTypeOption = parameterSetting && parameterSetting.elementType && parameterSetting.elementType.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    return columns && columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          isRequired: col.isRequired ? col.isRequired : false,
          dataIndex: col.dataIndex,
          option: elementTypeOption, // 单元格下拉数据
          title: col.title, // 单元格描述
          inputType: col.inputType, // 输入框类型
          editing: this.isEditing(record, type),
        }),
      };
    })
  }

  // 新增列表数据
  handleAddTableData = (dataSource, type) => {
    let { assessmentRowId, assessmentTemplateRowId, editingKey, elementRangeEditingKey } = this.state;
    let leg = dataSource && dataSource.length ? dataSource.length + 1 : 1;
    let arr = [];
    let newData = {};
    if (type === "elementRange") {
      newData = {
        key: leg,
        tempEleDataCode: "",
        tempEleDataDesc: "",
        tempEleDataValue: "",
        tempEleDataDefault: ""
      }
    } else {
      newData = {
        key: leg,
        tempElementDesc: "",
        tempEleTypeDesc: undefined,
        tempEleIsRequired: "N",
        tempEleTableSeqNo: "",
        tempEleTableItem: "N",
        tempEleTableWidth: ""
      };
    }
    arr.push(newData)
    if (type === "elementRange") {
      if (!assessmentTemplateRowId) {
        message.error("请先选择一条元素数据。")
        return;
      }
      if (!elementRangeEditingKey) {
        this.setState({
          elementRangeTableData: dataSource && dataSource.length > 0 ? [...dataSource, newData] : arr
        }, () => {
          this.setState({ elementRangeEditingKey: leg })
        })
      } else {
        message.info("为避免数据丢失，请保存后再新增。");
      }
    } else {
      if (!assessmentRowId) {
        message.error("请先选择一条元素。")
        return;
      }
      if (!editingKey) {
        this.setState({
          assessmentTemplateTableData: dataSource && dataSource.length > 0 ? [...dataSource, newData] : arr
        }, () => {
          this.setState({ editingKey: leg })
        })
      } else {
        message.info("为避免数据丢失，请保存后再新增。");
      }
    }
  }

  //上移
  moveUp = (keys, tableData, type) => {
    var keys = keys;
    var data = tableData;
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = 0; i < keys.length; i++) {
      if (keys[i] === 0) {
        newKeys.push(keys[i])
        message.warn('已经到顶了，无法再移动！')
        return
      }
      var curRowData = data[keys[i]]
      var curRowKey = curRowData.key
      var upRowData = data[keys[i] - 1]
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey
      data[keys[i]] = upRowData
      data[keys[i] - 1] = curRowData
      newKeys.push(keys[i] - 1)
    }
    if (type === "elementRange") {
      this.setState({
        elementRangeTableData: data,
        elementRangeSelectedRowKeys: newKeys
      })
    } else {
      this.setState({
        assessmentTemplateTableData: data,
        assessmentTemplateSelectedRowKeys: newKeys
      })
    }
  }

  //下移
  moveDown = (keys, tableData, type) => {
    var keys = keys;
    var data = tableData;
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = keys.length - 1; i >= 0; i--) {
      if (keys[i] === data.length - 1) {
        newKeys.push(keys[i])
        message.warn('已经到底了，无法再移动！')
        return
      }
      var curRowData = data[keys[i]]
      var upRowData = data[keys[i] + 1]
      var curRowKey = curRowData.key
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey
      data[keys[i]] = upRowData
      data[keys[i] + 1] = curRowData
      newKeys.push(keys[i] + 1)
    }
    if (type === "elementRange") {
      this.setState({
        elementRangeTableData: data,
        elementRangeSelectedRowKeys: newKeys
      })
    } else {
      this.setState({
        assessmentTemplateTableData: data,
        assessmentTemplateSelectedRowKeys: newKeys
      })
    }
  }

  // 上下移动
  handleMove = (status, type) => {
    const that = this;
    let { assessmentTemplateTableData, elementRangeTableData, assessmentTemplateSelectedRowKeys, elementRangeSelectedRowKeys } = this.state;
    let selectedRows = type === "elementRange" ? elementRangeSelectedRowKeys : assessmentTemplateSelectedRowKeys;
    let tableData = type === "elementRange" ? elementRangeTableData : assessmentTemplateTableData;
    if (status === 'up') {
      that.moveUp(selectedRows, tableData, type)
    } else if (status === 'down') {
      that.moveDown(selectedRows, tableData, type)
    }
  }

  // 键盘事件
  handleOnKeydown = (e, type) => {
    var e = window.event || e;
    switch (e.keyCode) {
      case 38: //上
        this.handleMove("up", type)
        break;
      case 40: //下
        this.handleMove("down", type)
        break;
    }
  }

  // 页码改变的回调，参数是改变后的页码及每页条
  handleAssessmentChangePage = (page, pageSize) => {
    this.setState({ assessmentPageSize: pageSize, assessmentPage: page }, () => {
      this.getAssessmentTableData();
    })
  };

  // 条数改变的回调
  handleAssessmentChangePageSize = (current, size) => {
    this.setState({ assessmentPageSize: size, assessmentPage: 1 }, () => {
      this.getAssessmentTableData();
    })
  };

  handleLocChangePageSize = (page, pageSize) => {
    this.setState({ locPageSize: pageSize, locPage: page }, () => {
      this.getLocTableData();
    })
  }

  handleLocChangePage = (current, size) => {
    this.setState({ locPageSize: size, locPage: 1 }, () => {
      this.getLocTableData();
    })
  }

  // 本地删除数据
  deleteRow = (key, type) => {
    const dataSource = JSON.parse(JSON.stringify(type === "assessmentTemplate" ? this.state.assessmentTemplateTableData : this.state.elementRangeTableData));
    let tableData = dataSource.filter(item => item.key !== key);
    if (type === "assessmentTemplate") {
      this.setState({ assessmentTemplateTableData: tableData });
    } else {
      this.setState({ elementRangeTableData: tableData });
    }
  }

  // 删除评估表行数据
  handleAssessmentTemplateDelete = () => {
    let { assessmentTemplateTableData, assessmentTemplateSelectedRows, editingKey } = this.state;
    let isEditing = false;
    for (var i = 0; i < assessmentTemplateSelectedRows.length; i++) {
      if (assessmentTemplateSelectedRows[i].key === editingKey) {
        isEditing = true;
        break
      }
    }
    if (!isEditing) {
      let selectRows = [], selectRowKeys = [];
      for (var i = 0; i < assessmentTemplateTableData.length; i++) {
        for (var j = 0; j < assessmentTemplateSelectedRows.length; j++) {
          if (assessmentTemplateTableData[i].key === assessmentTemplateSelectedRows[j].key) {
            if (assessmentTemplateTableData[i].tempElementID) {
              selectRows.push(assessmentTemplateTableData[i].tempElementID)
              selectRowKeys.push(assessmentTemplateTableData[i])
            } else {
              this.deleteRow(assessmentTemplateTableData[i].key, "assessmentTemplate"); /// 本地删除
            }
          }
        }
      }
      this.setState({ assessmentTemplateSelectedRowKeys: [], assessmentTemplateSelectedRows: [] })
      if (selectRows && selectRows.length > 0) {
        let data = {
          params: [{
            tempElementIDs: selectRows,
          }]
        }
        $http.post('urlS', this, {
          code: "04220017",
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              for (var k = 0; k < selectRowKeys.length; k++) {
                this.deleteRow(selectRowKeys[k].key, "assessmentTemplate"); /// 本地删除
              }
              message.success(res.errorMessage);
            }
          }
        })
      }
    } else {
      message.info("为避免数据丢失，请保存后再新增。");
    }
  }

  // 删除元素值域
  handleElementRangeDelete = () => {
    let { elementRangeTableData, elementRangeSelectedRows, elementRangeEditingKey } = this.state;
    let isEditing = false;
    for (var i = 0; i < elementRangeSelectedRows.length; i++) {
      if (elementRangeSelectedRows[i].key === elementRangeEditingKey) {
        isEditing = true;
        break
      }
    }
    if (!isEditing) {
      let selectRows = [], selectRowKeys = [];
      for (var i = 0; i < elementRangeTableData.length; i++) {
        for (var j = 0; j < elementRangeSelectedRows.length; j++) {
          if (elementRangeTableData[i].key === elementRangeSelectedRows[j].key) {
            if (elementRangeTableData[i].tempEleDataID) {
              selectRows.push(elementRangeTableData[i].tempEleDataID);
              selectRowKeys.push(elementRangeTableData[i]);
            } else {
              this.deleteRow(elementRangeTableData[i].key, "elementRange"); /// 本地删除
            }
          }
        }
      }
      this.setState({ elementRangeSelectedRowKeys: [], elementRangeSelectedRows: [] })
      if (selectRows && selectRows.length > 0) {
        let data = {
          params: [{
            tempEleDataIDs: selectRows,
          }]
        }
        $http.post('urlS', this, {
          code: "04220018",
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              message.success(res.errorMessage);
              for (var k = 0; k < selectRowKeys.length; k++) {
                this.deleteRow(selectRowKeys[k].key, "elementRange"); /// 本地删除
              }
            }
          }
        })
      }
    } else {
      message.info("为避免数据丢失，请保存后再新增。");
    }
  }

  // 查询授权需要使用的科室列表数据
  handleQueryLocTable = () => {
    this.setState({ locPage: 1 }, () => {
      this.getLocTableData();
    })
  }

  // 获取授权需要使用的科室列表数据
  getLocTableData = () => {
    let { assessmentRowId, locDesc } = this.state;
    let data = {
      params: [{
        tempLocConfigID: assessmentRowId,
        searchWords: locDesc
      }]
    }
    $http.post('urlS', this, {
      code: "04220013",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let locTableData = res.result && res.result.data && res.result.data.length > 0 ? res.result.data : [];
          for (var i = 0; i < locTableData.length; i++) {
            locTableData[i].key = i + 1;
          }
          this.setState({ locTableData, locTotal: res.result.TotalCount })
        } else {
          this.setState({ locTableData: [], locTotal: 0 })
        }
      }
    })
  }

  // 科室名称change
  handleLocDescChange = e => {
    this.setState({ locDesc: e.target.value })
  }

  // 科室类型
  handleLocTypeChange = e => {
    this.setState({ locType: e })
  }

  // 科室保存
  handleLocSave = () => {
    let { assessmentRowId, tempLocConfigLocID } = this.state;
    let data = {
      params: [{
        templateID: assessmentRowId,
        tempLocConfigLocID
      }],
    }
    $http.post('urlS', this, {
      code: "04220012",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          console.log(res)
        }
      }
    })
  }

  render() {
    let { formName, formUsage, isEffective, assessmentTableData, locDesc, locType, locTableData, parameterSetting, assessmentTemplateTableData, elementRangeTableData, assessmentPage,
      assessmentTotal, loading, locPage, locTotal, assessmentTemplateSelectedRowKeys, assessmentTemplateSelectedRows, elementRangeSelectedRowKeys, elementRangeSelectedRows, assessmentRowId,
      assessmentTemplateRowId, assessmentRowData, locSelectedRowKeys, locSelectedRows
    } = this.state;

    // 按科室查询
    let formUsageOption = parameterSetting && parameterSetting.locList && parameterSetting.locList.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })

    // 科室类型下拉数据
    let locTypeOption = parameterSetting && parameterSetting.locType && parameterSetting.locType.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })

    // 科室列表选择行操作
    let locRowSelection = {
      selectedRowKeys: locSelectedRowKeys,
      selectedRows: locSelectedRows,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ locSelectedRowKeys: selectedRowKeys, locSelectedRows: selectedRows })
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        this.setState({ locSelectedRows: selectedRows })
      },
    };

    // 评估模板table
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    let assessmentTemplateRowSelection = {
      selectedRowKeys: assessmentTemplateSelectedRowKeys,
      selectedRows: assessmentTemplateSelectedRows,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ assessmentTemplateSelectedRowKeys: selectedRowKeys, assessmentTemplateSelectedRows: selectedRows })
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        this.setState({ assessmentTemplateSelectedRows: selectedRows })
      },
    };

    let elementRangeRowSelection = {
      selectedRowKeys: elementRangeSelectedRowKeys,
      selectedRows: elementRangeSelectedRows,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ elementRangeSelectedRowKeys: selectedRowKeys, elementRangeSelectedRows: selectedRows });
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        this.setState({ elementRangeSelectedRows: selectedRows })
      },
    }

    return (
      <div className="mobile-care-form-settings">
        <Row>
          <Col span={18}>
            <div style={{ paddingRight: '6px', position: 'relative', height: store.getState().tableHeight.y + 243 + 'px' }}>
              <Card
                size="small"
                title={<div className="card-title-left-icon"><div></div>移动护理表单设置</div>}
                className="mcf-left-card"
              >
                <Row>
                  <Col span={8} style={{ borderRight: "1px solid #e8e8e8" }}>
                    <div>
                      <div style={{ marginBottom: '12px', display: 'flex', alignItems: 'center' }}>
                        <span className="custom-form-item-label" style={{ width: "99px" }}>按科室查询：</span>
                        <Select
                          value={formUsage}
                          onChange={this.handleFormUsageChange}
                          showSearch optionFilterProp="seatchprop"
                          allowClear placeholder="请选择" style={{ width: '160px', marginRight: '12px' }}
                          className="custom-form-item-input"
                        >
                          {formUsageOption}
                        </Select>
                        <Checkbox
                          checked={isEffective}
                          onChange={this.handleIsEffectiveChange}
                        >
                          仅显示生效
                        </Checkbox>
                      </div>
                      <div style={{ marginBottom: '12px', display: 'flex', alignItems: 'center' }}>
                        <span className="custom-form-item-label" style={{ width: "99px" }}>表单名称：</span>
                        <Input value={formName} allowClear
                          onChange={this.handleFormNameChange}
                          onPressEnter={this.getAssessmentTableData}
                          placeholder="支持代码、名称" style={{ width: '160px' }}
                          className="custom-form-item-input"
                        />
                        <Button
                          icon="plus"
                          type="primary"
                          style={{ marginLeft: "12px" }}
                          onClick={this.handleAddEvaluationForm}
                        >添加评估表</Button>
                      </div>
                    </div>
                    <div className="mcf-left-table">
                      <Table
                        bordered
                        dataSource={assessmentTableData}
                        columns={this.assessmentColumns}
                        pagination={false}
                        onRow={this.handleAssessmentClickRow}
                        rowClassName={this.setAssessmentRowClassName}
                        scroll={{ x: 500, y: store.getState().tableHeight.y + 10 }}
                        className="table-body-height"
                      />
                      <CommonPagination
                        size="small"
                        current={assessmentPage}
                        total={assessmentTotal}
                        search='search'
                        onShowSizeChange={this.handleAssessmentChangePageSize}
                        complete={false}
                        dataSource={assessmentTableData}
                        loading={loading}
                        onChange={this.handleAssessmentChangePage}
                        pageSize={false} />
                    </div>
                  </Col>
                  <Col span={16}>
                    <div
                      tabIndex={1}
                      onKeyDown={this.handleOnKeydown}
                      style={{ marginBottom: "12px", outline: 'none' }}
                    >
                      <div className="mcf-center-title">{assessmentRowData && assessmentRowData.templateDesc ? assessmentRowData.templateDesc : "请在左侧选择需要操作的评估表"}</div>
                      <div className="mcf-center-operation">
                        <div className="mcf-center-operation-btn" style={{ marginLeft: "12px" }}>
                          <li onClick={() => this.handleAddTableData(assessmentTemplateTableData)} className={!assessmentRowId ? 'color999' : 'color333'}>
                            <Icon className='doctor-add-splice' />
                            <span>新增</span>
                          </li>
                          <Divider type="vertical" />
                          <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleAssessmentTemplateDelete}>
                            <li className={assessmentTemplateSelectedRows && assessmentTemplateSelectedRows.length > 0 ? 'color333' : 'color999'}>
                              <Icon className='doctor-delete-splice' />
                              <span>删除</span>
                            </li>
                          </Popconfirm>
                          <Divider type="vertical" />
                          <li onClick={() => this.handleMove("up")} className={assessmentTemplateSelectedRows && assessmentTemplateSelectedRows.length > 0 ? 'color333' : 'color999'}>
                            <Icon className='doctor-up-splice' />
                            <span>上移</span>
                          </li>
                          <Divider type="vertical" />
                          <li onClick={() => this.handleMove("down")} className={assessmentTemplateSelectedRows && assessmentTemplateSelectedRows.length > 0 ? 'color333' : 'color999'}>
                            <Icon className='doctor-down-splice' />
                            <span>下移</span>
                          </li>
                          {/* <EditableContext.Consumer>
                            {form => (
                              <Button
                                type="primary"
                                style={{ marginLeft: "12px" }}
                                onClick={() => this.handleAssessmentTemplateSave(form)}
                              >保存</Button>
                            )}
                          </EditableContext.Consumer> */}
                        </div>
                        <Search
                          placeholder="输入元素名称回车查询"
                          onSearch={value => this.getAssessmentTemplateTableData(value)}
                          style={{ width: 200 }}
                        />
                      </div>
                      <div className="mcf-center-table">
                        <EditableContext.Provider value={this.props.form}>
                          <Table
                            components={components}
                            bordered
                            pagination={false}
                            dataSource={assessmentTemplateTableData}
                            rowSelection={assessmentTemplateRowSelection}
                            columns={this.processingHeaderData(this.assessmentTemplateColumns)}
                            onRow={this.handleAssessmentTemplateOnRow}
                            rowClassName={this.setAssessmentTemplateRowClassName}
                            scroll={{ x: 650, y: store.getState().tableHeight.y / 2 + 2 }}
                            className="table-body-height"
                          />
                        </EditableContext.Provider>
                      </div>
                    </div>
                    <Card
                      size="small"
                      title={<div className="card-title-left-icon"><div></div>设置元素值域</div>}
                      className="mcf-center-card"
                      tabIndex={1}
                      onKeyDown={(e) => this.handleOnKeydown(e, "elementRange")}
                      style={{ outline: 'none' }}
                    >
                      <div className="mcf-center-operation">
                        <div className="mcf-center-operation-btn">
                          <li onClick={() => this.handleAddTableData(elementRangeTableData, "elementRange")} className={!assessmentTemplateRowId ? 'color999' : 'color333'}>
                            <Icon className='doctor-add-splice' />
                            <span>新增</span>
                          </li>
                          <Divider type="vertical" />
                          <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleElementRangeDelete}>
                            <li className={elementRangeSelectedRows && elementRangeSelectedRows.length > 0 ? 'color333' : 'color999'}>
                              <Icon className='doctor-delete-splice' />
                              <span>删除</span>
                            </li>
                          </Popconfirm>
                          <Divider type="vertical" />
                          <li onClick={() => this.handleMove("up", "elementRange")} className={elementRangeSelectedRows && elementRangeSelectedRows.length > 0 ? 'color333' : 'color999'}>
                            <Icon className='doctor-up-splice' />
                            <span>上移</span>
                          </li>
                          <Divider type="vertical" />
                          <li onClick={() => this.handleMove("down", "elementRange")} className={elementRangeSelectedRows && elementRangeSelectedRows.length > 0 ? 'color333' : 'color999'}>
                            <Icon className='doctor-down-splice' />
                            <span>下移</span>
                          </li>
                          {/* <EditableContext.Consumer>
                            {form => (
                              <Button
                                type="primary"
                                style={{ marginLeft: "12px" }}
                                onClick={() => this.handleElementRangeSave(form)}
                              >保存</Button>
                            )}
                          </EditableContext.Consumer> */}
                        </div>
                      </div>
                      <EditableContext.Provider value={this.props.form}>
                        <Table
                          components={components}
                          rowClassName={() => 'editable-row'}
                          bordered
                          pagination={false}
                          rowSelection={elementRangeRowSelection}
                          dataSource={elementRangeTableData}
                          onRow={this.handleElementRangeOnRow}
                          columns={this.processingHeaderData(this.elementRangeColumns, "elementRange")}
                          scroll={{ x: 400, y: store.getState().tableHeight.y / 2 - 97 }}
                          className="table-body-height"
                        />
                      </EditableContext.Provider>
                    </Card>
                  </Col>
                </Row>
              </Card>
              <div style={{ width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%' }}></div>
            </div>
          </Col>
          <Col span={6}>
            <Card
              size="small"
              title={<div className="card-title-left-icon"><div></div>授权需要使用的科室</div>}
              className="mcf-right-card"
            >
              <div>
                <div>
                  <div style={{ marginBottom: '12px', display: 'flex', alignItems: 'center' }}>
                    <span className="custom-form-item-label" style={{ width: '99px' }}>科室名称：</span>
                    <Input
                      value={locDesc} allowClear
                      onChange={this.handleLocDescChange}
                      onPressEnter={this.handleQueryLocTable}
                      placeholder="支持代码、名称" style={{ width: '200px' }}
                      className="custom-form-item-input"
                    />
                  </div>
                  <div style={{ marginBottom: '12px', display: 'flex', alignItems: 'center' }}>
                    <span className="custom-form-item-label" style={{ width: '99px' }}>科室类型：</span>
                    <Select
                      value={locType}
                      onChange={this.handleLocTypeChange} showSearch optionFilterProp="seatchprop"
                      allowClear placeholder="请选择" style={{ width: '200px' }}
                      className="custom-form-item-input"
                    >
                      {locTypeOption}
                    </Select>
                    <Button
                      type="primary"
                      style={{ marginLeft: "12px" }}
                      onClick={this.handleLocSave}
                    >保存</Button>
                  </div>
                </div>
                <Table
                  bordered
                  dataSource={locTableData}
                  columns={this.locColumns}
                  pagination={false}
                  rowSelection={locRowSelection}
                  scroll={{ x: 300, y: store.getState().tableHeight.y + 10 }}
                  className="table-body-height"
                />
                <CommonPagination
                  size="small"
                  current={locPage}
                  total={locTotal}
                  search='search'
                  onShowSizeChange={this.handleLocChangePageSize}
                  complete={false}
                  dataSource={locTableData}
                  loading={loading}
                  onChange={this.handleLocChangePage}
                  pageSize={false} />
              </div>
            </Card>
          </Col>
        </Row>
        <AddCareForm
          onRef={this.onRef}
          handleQuery={this.getAssessmentTableData}
        />
      </div>
    );
  }
}

const MobileCareFormSettingsForm = Form.create()(MobileCareFormSettings);
export default MobileCareFormSettingsForm;
