// 会诊字典
import React from 'react';
import { Card, Row, Col, Icon, Table, Button, Input, message, Switch, Divider, Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
import { Util } from '../../tools';
import './style/style.less';
import store from 'store';
import CommonPagination from 'components/pagination/index';

let user;
export default class NeedAtentiontable extends React.Component {
  cacheOriginData = {};
  constructor(props) {
    super(props);
    user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    this.state = {
      show: false,
      size: 'small',
      data: [],//列表数据
      rowId: "",//表格行id 设置颜色
      index: 0,
      loading: false,
      dataSource: [],//列表数据
      total: 0,//分页数据
      page: 1,
      pageSize: 10,
      detailTotal: 0, // 分页数据
      page2: 1,
      pageSize2: 10,
      conDictID: '',
    }
  };
  initData() {
    const auditFlag = this.props.flag;
    let columnTitle;
    if (auditFlag === "R") {
      columnTitle = ["是否显示", "启用"];
    } else {
      columnTitle = ["启用", "启用"];
    }
    this.columns = [
      {
        key: 'conDictCode',
        title: '代码',
        dataIndex: 'conDictCode',
        align: "center",
        width: '130px',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                onClick={this.handleStopPropagation}
                value={text}
                autoFocus
                onChange={e => this.handleFieldChange(e, 'conDictCode', record)}
                placeholder="代码"
              />);
          }
          return text;
        }
      },
      {
        key: 'conDictDesc',
        title: '描述',
        dataIndex: 'conDictDesc',
        align: "center",
        width: '200px',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                onClick={this.handleStopPropagation}
                value={text}
                onChange={e => this.handleFieldChange(e, 'conDictDesc', record)}
                placeholder="描述"
              />)
          }
          return text;
        }
      },
      {
        key: 'conDictStatus',
        title: columnTitle[0],
        //title: '启用',
        dataIndex: 'conDictStatus',
        align: "center",
        width: '130px',
        render: (text, record, index) => {
          if (record.editable) {
            return (
              <Switch
                onClick={this.handleStopPropagation}
                defaultChecked={(record.conDictStatus == 'N' || record.conDictStatus == '未启用') ? false : true}
                onChange={(val, e) => this.handleSwitchChange(val, e, 'conDictStatus', record)}

              />
            )
          }
          return text;
        },
      }, {
        title: '操作',
        dataIndex: 'operation',
        key: 'action',
        align: "center",
        width: '130px',
        render: (text, record, index) => {
          const { loading } = this.state;
          if (!!record.editable && loading) {
            return null;
          }
          if (record.editable) {
            return (
              <span>
                <a onClick={(e) => this.saveRow(e, record)}>保存</a>
                <Divider type="vertical" />
                <a onClick={(e) => this.cancel(e, record)}>取消</a>
              </span>
            )
          }
          return (
            <span>
              <a onClick={(e) => this.toggleEditable(e, record)}>编辑</a>
              <Divider type="vertical" />
              <Popconfirm title="是否要删除此行"
                onConfirm={(e) => this.remove(record.conDictID, e)}>
                <a>删除</a>
              </Popconfirm>
            </span>
          )
        },
      }];
    this.modalColumns = [
      {
        key: 1,
        title: '代码',
        dataIndex: 'conDictItemCode',
        align: "center",
        width: '130px',
        render: (text, record) => {
          if (record.editableUpdate) {
            return (
              <Input
                value={text}
                onClick={this.handleStopPropagation}
                autoFocus
                onChange={e => this.handleFieldChange1(e, 'conDictItemCode', record)}
                placeholder="代码"
              />);
          }
          return text;
        }
      },
      {
        key: 2,
        title: '描述',
        dataIndex: 'conDictItemDesc',
        align: "center",
        width: '130px',
        render: (text, record) => {
          if (record.editableUpdate) {
            return (
              <Input
                value={text}
                onClick={this.handleStopPropagation}
                onChange={e => this.handleFieldChange1(e, 'conDictItemDesc', record)}
                placeholder="描述"
              />)
          }
          return text;
        }
      },
      {
        key: 3,
        // title: '启用',
        title: '默认值',
        dataIndex: 'conDictItemStatus',
        align: "center",
        width: '130px',
        render: (text, record, index) => {
          if (record.editableUpdate) {
            return (
              <Input
                value={text}
                onClick={this.handleStopPropagation}
                autoFocus
                onChange={e => this.handleFieldChange1(e, 'conDictItemStatus', record)}
                placeholder="默认值"
              />);
          }
          return text;
        }
      },
      {
        key: 4,
        // title: '启用',
        title: '会诊审核',
        dataIndex: 'conDictItemValue',
        align: "center",
        width: '130px',
        render: (text, record, index) => {
          if (record.editableUpdate) {
            return (
              <Switch
                onClick={this.handleStopPropagation}
                defaultChecked={(Util.isEmpty(record.conDictItemValue)) ? false : true}
                onChange={(val, e) => this.handleSwitchChange1(val, e, 'conDictItemValue', record)}
              />
            )
          }
          return text;
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'action',
        align: "center",
        render: (text, record, index) => {
          const { loading } = this.state;
          if (!!record.editableUpdate && loading) {
            return null;
          }
          if (record.editableUpdate) {
            return (
              <span>
                <a onClick={(e) => this.saveNewRowAdd(e, record)}>保存</a>
                <Divider type="vertical" />
                <a onClick={(e) => this.cancell(e, record)}>取消</a>
              </span>
            )
          } else {
            return (
              <span>
                <a onClick={(e) => this.toggleEditableUpdate(e, record)}>编辑</a>
                <Divider type="vertical" />
                <Popconfirm title="是否要删除此行"
                  onConfirm={(e) => this.removeDelete(record.conDictItemID, e)} >
                  <a>删除</a>
                </Popconfirm>
              </span>
            )
          }
        }
      }];
  }
  componentDidMount() {
    // 初始化设置table的高度以及表体的高度
    document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
    // 初始化数据
    this.handleQuery();
    this.initData();

  }

  // 阻止默认事件
  handleStopPropagation = (e) => {
    if (typeof e == 'object') {
      e.stopPropagation();
    }
  }

  //查询
  handleQuery = () => {
    let { page, pageSize } = this.state;
    let data = {
      params: [{
        power: "list",
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
        sortColumn: 'code',
        sortOrder: 'asc'
      }]
    }
    $http.post('urlS', this, {
      code: "04090003",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ data: res.result.Data, total: res.result.TotalCount, loading: false })
        } else {
          message.error('查询失败：' + res.errorMessage);
        }
      }
    })
  }

  //下拉框数据修改
  onSelectChange(index, fieldName, value) {
    let { data } = this.state;
    data[index][fieldName] = value;
    this.setState({ data: data });

  }

  //字典项目新增 
  newAdd = () => {
    //debugger
    const { dataSource } = this.state;
    const newData = dataSource.map((item) => ({ ...item }));
    newData.push({
      key: `NEW_TEMP_ID_${this.state.index}`,
      conDictItemCode: '',
      conDictItemDesc: '',
      onDictItemStatus: 'N',
      editableUpdate: true,
      isAdd: true
    });
    this.setState({
      dataSource: newData,
      index: this.state.index + 1,
    });
  }

  //新增
  saveRowAdd(e, key, rank) {
    e.persist();
    let data = {
      params: []
    };
    const target = this.getRowByKeyAdd(key) || {};
    if (!target.conDictItemCode || !target.conDictItemDesc) {
      message.error('请填写完整配置信息');
      e.target.focus();
      this.setState(
        { loading: false, }
      )
    }
    delete target.isAdd;
    let obj = JSON.parse(JSON.stringify(target));
    obj.type = 'insert';
    obj.conDictID = this.state.rowId;
    obj.updateUserID = user.userID;
    if (rank === "C") { }
    obj.saveType = rank;
    data.params.push(Util.disposeData(obj));
    $http.post('urlADS', this, {
      code: '04090002',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('新增成功');
          this.handleQueryFind();
        }
      }
    });
  }
  //字典更新
  saveNewRowAdd = (e, record) => {
    e.persist();
    //debugger
    let data = {
      params: []
    };
    if (!record.conDictItemCode || !record.conDictItemDesc) {
      message.error('请填写完整配置信息');
      e.target.focus();
      this.setState(
        { loading: false, }
      )
    }
    let obj = JSON.parse(JSON.stringify(record));
    obj.conDictID = this.state.rowId;
    obj.conDictItemID = record.conDictItemID;
    obj.updateUserID = user.userID;
    data.params.push(Util.disposeData(obj));
    $http.post('urlADS', this, {
      code: '04090002',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('更新成功');
          this.handleQueryFind();
        }
      }
    });
  }
  //新增
  newMember = () => {
    //debugger
    const { data } = this.state;
    const newData = data.map((item) => ({ ...item }));
    newData.push({
      key: `NEW_TEMP_ID_${this.state.index}`,
      conDictCode: '',
      conDictDesc: '',
      conDictStatus: 'N',
      editable: true,
      isNew: true,
    });
    this.setState({
      data: newData,
      index: this.state.index + 1,
    });
  }

  //新增
  saveRow(e, record) {
    e.persist();
    let data = {
      params: []
    };
    if (!record.conDictCode || !record.conDictDesc) {
      message.error('请填写完整配置信息');
      e.target.focus();
      this.setState(
        { loading: false, }
      )
    }
    delete record.isNew;
    let obj = JSON.parse(JSON.stringify(record));
    obj.type = 'insert';
    obj.updateUserID = user.userID;
    data.params.push(Util.disposeData(obj));
    $http.post('urlADS', this, {
      code: '04090001',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('保存成功');
          this.handleQuery();
        }
      }
    });
  }

  //取消
  cancel(e, record) {
    e.preventDefault();
    record.editable = false;
    this.forceUpdate();
  }
  cancell(e, record) {
    e.preventDefault();
    record.editableUpdate = false;
    this.forceUpdate();
  }
  //获取操作行数据对象
  getRowByKey(key, newData) {
    const { data } = this.state;
    return (newData || data).filter(item => item.key === key)[0];
  }
  //获取操作行数据对象
  getRowByKeyAdd(key, newData) {
    const { dataSource } = this.state;
    return (newData || dataSource).filter(item => item.key === key)[0];
  }
  //文本框数据修改
  handleFieldChange(e, fieldName, record) {
    record[fieldName] = e.target.value;
    this.forceUpdate();
  }
  //文本框数据修改
  handleFieldChange1(e, fieldName, record) {
    record[fieldName] = e.target.value;
    this.forceUpdate();
  }
  //添加-删除
  cut(key) {
    const { data } = this.state;
    const { onChange } = this.props;
    const newData = data.filter(item => item.key !== key);
    this.setState({ data: newData });
    // onChange(newData);
  }
  //添加-删除
  cut1(key) {
    const { dataSource } = this.state;
    const { onChange } = this.props;
    const newData = dataSource.filter(item => item.key !== key);
    this.setState({ dataSource: newData });
    // onChange(newData);
  }
  handleSwitchChange = (val, e, el, record) => {
    this.handleStopPropagation(e)
    record[el] = val ? "Y" : "N";
    //console.log(record[el])
    this.forceUpdate();
  }
  handleSwitchChange1(val, e, el, record) {
    this.handleStopPropagation(e)
    record[el] = val ? "Y" : "N";
    if (el == 'conDictItemValue') {
      //record[el]=
    }
    this.forceUpdate();
  }
  //编辑
  toggleEditable = (e, record) => {
    e.preventDefault();
    record.editable = !record.editable;
    this.forceUpdate();
  }
  //编辑
  toggleEditableUpdate = (e, record) => {
    e.preventDefault();
    record.editableUpdate = !record.editableUpdate;
    this.forceUpdate();
  }


  //删除
  remove(id) {
    // debugger
    if (id === "") {
      message.success('请选中删除行');
      return;
    }
    let tempObj = {};
    tempObj.conDictID = id;
    tempObj.updateUserID = user.userID;
    let obj = JSON.parse(JSON.stringify(tempObj));
    let data = {
      params: []
    };
    data.params.push(Util.disposeData(obj));
    $http.post('urlADS', this, {
      code: '04090005',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('删除成功');
          this.handleQuery();
        }
      },
    });
  }
  //删除
  removeDelete(id) {
    // debugger
    if (id === "") {
      message.success('请选中删除行');
      return;
    }
    let tempObj = {};
    tempObj.conDictItemID = id;
    tempObj.updateUserID = user.userID;
    let obj = JSON.parse(JSON.stringify(tempObj));
    let data = {
      params: []
    };
    data.params.push(Util.disposeData(obj));
    $http.post('urlADS', this, {
      code: '04090006',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('删除成功');
          this.handleQueryFind();
        }
      },
    });
  }

  //字典项目查询
  handleQueryFind = () => {
    if ((this.state.rowId == '') || (this.state.rowId == undefined)) {
      return;
    }
    let { page2, pageSize2 } = this.state;
    let data = {
      params: [{
        conDictID: this.state.rowId,
        power: "list",
      }],
      pagination: [{
        pageSize: pageSize2,
        currentPage: page2,
        sortColumn: 'code',
        sortOrder: 'asc'
      }]
    }
    $http.post('urlS', this, {
      code: "04090004",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {

          this.setState({ dataSource: res.result.Data, detailTotal: res.result.TotalCount, loading: false })
        } else {
          message.error('查询失败：' + res.errorMessage);
        }
      }
    })
  }

  //点击行，渲染当前行样式
  onClickRow = (record) => {
    return {
      onClick: () => {
        //未选择任何记录
        if (this.state.rowId === "") {
          this.setState({
            rowId: record.conDictID,
          }, () => {
            this.handleQueryFind();
          });
        } else {
          //选择其他记录
          if (this.state.rowId !== record.conDictID) {
            this.setState({
              rowId: record.conDictID,
            }, () => {
              this.handleQueryFind();
            });
          } else {
            //二次点击当前选中的记录
            this.setState({
              rowId: "",
              dataSource: []
            });
          }
        }
        //console.log("传递",record.conDictID,this.state.rowId)
        this.setState({
          conDictID: this.state.rowId
        })
      },

    };
  }

  //设置点击row颜色 --左侧表格
  setRowClassName = (record) => {
    return record.conDictID === this.state.rowId ? 'clickRowStyle' : '';
  }

  // 页码改变的回调，参数是改变后的页码及每页条数 需关注医嘱
  onChange = (page, pageSize) => {
    this.setState({ page: page, pageSize: pageSize }, () => {
      // 重新调用查询方法
      this.handleQuery();
    });
  };

  onShowSizeChange = (current, size) => {
    this.setState({ page: 1, pageSize: size }, () => {
      // 重新调用查询方法
      this.handleQuery();
    })
  };

  // 页码改变的回调，参数是改变后的页码及每页条数 执行记录
  onChange2 = (page, pageSize) => {
    this.setState({ page2: page, pageSize2: pageSize }, () => {
      // 重新调用查询方法
      this.handleQueryFind();
    });
  };

  onShowSizeChange2 = (current, size) => {
    this.setState({ page2: 1, pageSize2: size }, () => {
      // 重新调用查询方法
      this.handleQueryFind();
    })
  };
  // 显示分页总条数
  showTotal(total) {
    return `共 ${total} 条`;
  }
  packUpHandle = () => {
    this.setState({ show: !this.state.show, span: 24 })
  };
  render() {
    const { loading, data } = this.state;
    let tableHeight;
    if (data.length === 0) {
      tableHeight = 200;
    } else {
      tableHeight = "auto";
    }
    return (
      <div className='detail1'>
        <Row className="table-body-height">
          <Col span={12} style={{ display: this.state.show ? 'none' : '' }} className={!this.state.show ? "animate-wrap active down-in" : "animate-wrap"}>
            <Card
              size="small"
              title="字典类型"
              headStyle={{ background: 'rgb(66, 185, 131)' }}
            >
              <div className="detail-left">
                <Row>
                  <Col span={24}>
                    <div>
                      <Button type="primary" onClick={this.newMember}>新增</Button>
                    </div>
                    <br />
                    <Table
                      dataSource={this.state.data}
                      columns={this.columns}
                      pagination={false}
                      onRow={this.onClickRow}
                      rowClassName={this.setRowClassName}
                      loading={this.state.loading}
                      bordered
                      scroll={{ x: 590, y: store.getState().tableHeight.y + 44 }}
                    />
                    <CommonPagination
                      size={this.state.size}
                      current={this.state.page}
                      total={this.state.total}
                      search={this.state.search}
                      onShowSizeChange={this.onShowSizeChange.bind(this)}
                      complete={true}
                      dataSource={this.state.data}
                      loading={this.state.loading} onChange={this.onChange.bind(this)} />

                  </Col>
                </Row>
              </div>
            </Card>
          </Col>
          <Col span={this.state.show ? 24 : 12}>
            <Card
              size="small"
              title={<span><Icon onClick={this.packUpHandle} type={this.state.show ? 'double-right' : 'double-left'} />字典项目</span>}
              headStyle={{ background: 'rgb(66, 185, 131)' }}

            >
              <div>
                <Row>
                  <Col span={24}>
                    <div>
                      <Button type="primary" onClick={this.newAdd}>新增</Button>&nbsp;&nbsp;&nbsp;&nbsp;
                    </div>
                    <br />
                  </Col>
                </Row>
                <Table
                  dataSource={this.state.dataSource}
                  columns={this.modalColumns}
                  pagination={false}
                  rowKey={(row) => {
                    return row.conDictItemID
                  }}
                  rowClassName={record => (record.editableUpdate ? 'record' : '')}
                  bordered
                  scroll={{ x: 650, y: store.getState().tableHeight.y + 44 }}
                />
                <CommonPagination
                  size={this.state.size}
                  current={this.state.page2}
                  total={this.state.detailTotal}
                  search={this.state.search}
                  onShowSizeChange={this.onShowSizeChange.bind(this)}
                  complete={true}
                  dataSource={this.state.dataSource}
                  loading={this.state.loading} onChange={this.onChange.bind(this)} />

              </div>
            </Card>
          </Col>
        </Row>
      </div>
    )
  }
}