import React , { Component ,Fragment } from 'react';
import '../../assets/css/system.css';
import { Util } from '../../tools';
import store from '../../store';
import { $http } from '../../containers/config/https';
import { 
  Table, Input, Popconfirm ,Divider ,Button ,Collapse ,Row, Col ,message ,Pagination ,Switch ,Checkbox ,Select 
 } from 'antd';
 import './style/index.less'

let user;
const Option = Select.Option;

export default class DrawAuditModal extends React.Component {
  cacheOriginData = {};
    constructor(props) {
      user= window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
      super(props);
      this.state = {
        data: [],
        loading: false,
        value: props.value,
        hospID : user.hospID,
        hospital : [],
        index: '',
      };      
      this.style ={
        td : {
          paddingTop: 13 ,
          paddingBottom: 12.5 ,
        }
      };
      this.type = props.flag;
    }

    componentDidMount() {
      this.getHospital();
      this.initData();
      this.handleQuery();
    }

    initData () {
      const auditFlag = this.props.flag;
      let columnTitle;
      if (auditFlag === "R") {
           columnTitle = ["是否选中","是否显示"];
      } else {
           columnTitle = ["颜色","是否控制"];
      }
      this.columns = [
        {
          title: '名称',
          dataIndex: 'description',
          key: 'description',
          width: '10%',
          align: "center",
          render: (text, record) =>
          {
            if(record.editable){
              return ( 
              <Input
                value={text}
                autoFocus
                onChange={e => this.handleFieldChange(e, 'description', record.key)}
                //onKeyPress={e => this.handleKeyPress(e, record.key)}
                placeholder="名称"
              />);
            }
            return text;
          }
        }, {
          title: '代码',
          dataIndex: 'code',
          key : 'code',
          width: '15%',
          align: "center",
          render: (text, record) => {
            if(record.editable){
              return (
              <Input
                value={text}
                onChange={e => this.handleFieldChange(e, 'code', record.key)}
                //onKeyPress={e => this.handleKeyPress(e, record.key)}
                placeholder="代码"
              />)
            }
            return text;
          }
        },{
          title: '所属医院',
          dataIndex: 'hospitalDesc',
          key: 'hospitalDesc',
          width: '15%',
          align: 'center',
          render: (text ,record) => {
            if (record.editable) {
                return (
                  <Select style={{ width: 200 }} onChange={this.onSelectChange.bind(this,record.key)}>
                    {
                      this.state.hospital.map((item) => {
                        return (
                          <Option key={item.id} value={item.id + ""} title={item.descspell} >{item.descripts}</Option>
                        )
                      })
                    }
                  </Select>
                )
            }
            return text;
          }
        }, {
        title: columnTitle[0],
        dataIndex: 'defaultValue',
        key:'defaultValue',
        width: '15%',
        align: "center",
        render: (text, record, index) => {
          if(record.editable){
            if (auditFlag === "R") {
              return (
                <Checkbox
                defaultChecked={record.defaultValue == 'N'? false:true}
                onChange={(e) => this.handleSwitchChange(e,'defaultValue',record.key)}
                /> 
              )
            }
            return (
              <Input
                value={text}
                onChange={(e) => this.handleFieldChange(e, 'defaultValue',record.key)}
                //onKeyPress={(e) => this.handleKeyPress(e,record.key)}
                placeholder={columnTitle[0]}
              />
            )
          }
          return text;
        },
        }, {
        title : columnTitle[1],
        dataIndex : 'displayFlag',
        key : 'displayFlag',
        width : '10%',
        align: "center",
        render: (text, record, index) => {
          if(record.editable){
            return (
              <Checkbox
              defaultChecked={record.displayFlag == 'N'? false:true}
              onChange={(e) => this.handleSwitchChange(e,'displayFlag',record.key)}
              /> 
            )
          }
          return text;
        },
        }, {
        title : '显示顺序',
        dataIndex : 'seqNo',
        key: 'seqNo',
        width : '5%',
        align: "center",
        render: (text, record, index) => {
          if(record.editable){
            return(
              <Input
                value={text}
                onChange={(e) => this.handleFieldChange(e,'seqNo',record.key)}
                //onKeyPress={(e) => this.handleKeyPress(e,record.key)}
                placeholder='显示顺序'
              />
            )
          }
          return text;
        },
        },{
        title: '操作',          
        dataIndex: 'operation',
        key:'action',
        align: "center",
        render: (text, record, index) => {
          const { loading } = this.state;
          if(!!record.editable && loading){
            return null;
          }
          if (record.editable) {
            if (record.isNew) {
              return (
                <span>
                  <a onClick={(e) => this.saveRow(e,record.key,"C")}>添加(公共)</a>
                  <Divider type="vertical"/>
                  <a onClick={(e) => this.saveRow(e, record.key,"H")}>添加</a>
                  <Divider type="vertical"/>
                    <a onClick={() => this.cut(record.key)}>删除</a>
                </span>
              )
            }
            if (record.hospitalID){
                return (
                  <span>
                    <a onClick={(e) => this.saveNewRow(e,record.key,"H")}>保存</a>
                    <Divider type="vertical"/>
                    <a onClick={(e) => this.cancel(e,record.key)}>取消</a>
                </span>
                )
            }
            return (
              <span>
                <a onClick={(e) => this.saveNewRow(e,record.key,"C")}>保存(公共)</a>
                <Divider type="vertical"/>
                <a onClick={(e) => this.saveNewRow(e,record.key,"H")}>保存</a>
                <Divider type="vertical"/>
                <a onClick={(e) => this.cancel(e,record.key)}>取消</a>
              </span>
            )
          } 
          return (
            <span>
              <a onClick={(e) => this.toggleEditable(e, record.key)}>编辑</a>
              <Divider type="vertical"/>
              <Popconfirm title="是否要删除此行" onConfirm={() => this.remove(record.id)}>
                <a>删除</a>
              </Popconfirm>
            </span>
          )
        },
      }];
    } 
    
    getHospital = () => {
      let data = {
          params: [{
              hospID: user.hospID,
              logonGroupID: user.groupID,
              logonHospID: user.hospID,
          }]
      };

      $http.post('urlDeault', this, {
          code: "01040001",
          data: data,
          success: (res) => {
              if (+res.errorCode === 0) {
                  this.setState({ 
                    hospital: res.depDoctor, 
                    hospID: user.hospID 
                  })
              } else {
                  message.error('保存失败' + res.errorMessage);
              }
          }
      })
  }
    //查询
    handleQuery = () => {
      let data = {}
      data = {
        params: [{
            hospID: this.state.hospID,
            code: "",
            type : this.type
        }]
      }
      $http.post('urlS', this, {
        code: '04060006',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            for(var i = 0; i < res.result.length; i++) {
              res.result[i].key = i
            }
            this.setState({
              data: res.result, 
              loading: false,
              index: i ,
            })
          } else {
            // setTimeout(() => {
            //   this.setState({data: [], total: 0, loading: false})
            // }, 3000)
          }
        }
      })
    }
    //回车保存，暂时不使用
    handleKeyPress(e, key) {
      if (e.key === 'Enter') {
        this.saveRow(e, key);
      }
    }
    //新增
    newMember = () => {
      //debugger
      const { data } = this.state;
      const newData = data.map( (item) => ({...item}));
      newData.push({
        key: `NEW_TEMP_ID_${this.state.index}`,
        code: '',
        defaultValue: '',
        description: '',
        displayFlag: 'N',
        hospitalDesc: '',
        hospitalID: '',
        seqNo: '',
        editable: true,
        isNew: true,
      });
      this.setState({ 
        data : newData,
        index: this.state.index + 1,
      });
    }
    //获取操作行数据对象
    getRowByKey(key, newData) {
      const { data } = this.state;
      return (newData || data).filter(item => item.key === key)[0];
    }
    //文本框数据修改
    handleFieldChange(e, fieldName, key) {
      const { data } = this.state;
      const newData = data.map(item => ({ ...item }));
      const target = this.getRowByKey(key, newData);
      if (target) {
        target[fieldName] = e.target.value;
        this.setState({ data: newData });
      }
    }
    //下拉框数据修改
    onSelectChange(key , value ){
      let fieldName = "hospitalID" ;
      const { data } = this.state;
      const newData = data.map(item => ({ ...item }));
      const target = this.getRowByKey(key, newData);
      if (target) {
        target[fieldName] = value;
        this.setState({ data: newData });
      }
   }

   handleSwitchChange(e, fieldName, key){
    const { data } = this.state;
    const newData = data.map(item => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
        target[fieldName] = e.target.checked;
        
        this.setState({ data: newData });
    }
}


    //编辑
    toggleEditable = (e , key) => {
      e.preventDefault();
      const { data } = this.state;
      const newData = data.map(item => ({ ...item }));
      const target = this.getRowByKey(key, newData);
      if (target) {
        if (!target.editable) {
          this.cacheOriginData[key] = { ...target};
        }
        target.editable = !target.editable;
        this.setState({
          data : newData,
        })
      }

    }
    //新增
    saveRow(e, key , rank){
      e.persist();
      let data = {
        params : []
      };
      const target = this.getRowByKey(key) || {};
      if(!target.description || !target.code ) {
        message.error('请填写完整配置信息');
        e.target.focus();
        this.setState(
          {loading : false,}
        )
      }
      delete target.isNew;
      let obj = JSON.parse(JSON.stringify(target));
      obj.type = this.type;
      obj.updateUserID = user.userID;
      if (rank === "C") {obj.hospitalID = "";}
      obj.saveType = rank;
      data.params.push(Util.disposeData(obj));
      $http.post('urlADS', this, {
        code: '04060008',
        data: data,
        success : function(res){
          if (+res.errorCode === 0) {
            message.success('新增成功');
            this.handleQuery();
          }
        }
      });
    }
    //删除
    remove(id){
      //debugger
      if (id === "") {
        message.success('请选中删除行');
        return;
      }
      let tempObj = {};
      tempObj.id=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 : '04060009',
        data : data,
        success : function(res){
          if (+res.errorCode === 0) {
            message.success('删除成功');
            this.handleQuery();
          }
        },
      });
    }

    //更新
    saveNewRow =(e,key,rank) =>{
      e.persist();
      //debugger
      let data = {
        params : []
      };
      const target = this.getRowByKey(key) || {};
      if(!target.description || !target.code ) {
        message.error('请填写完整配置信息');
        e.target.focus();
        this.setState(
          {loading : false,}
        )
      }
      let obj = JSON.parse(JSON.stringify(target));
      //if(obj.displayFlag ==="Y")  return  obj.displayFlag
      obj.type = this.type;
      obj.updateUserID = user.userID;
      if (rank === "C") {obj.hospitalID = "";}
      obj.saveType = rank;
      data.params.push(Util.disposeData(obj));
      $http.post('urlADS', this, {
        code: '04060008',
        data: data,
        success : function(res){
          if (+res.errorCode === 0) {
            message.success('更新成功');
            this.handleQuery();
          }
        }
      });
    }

    //取消
    cancel(e, key){
      this.clickedCancel = true;
      e.preventDefault();
      const { data } = this.state;
      const newData = data.map((item) => ({ ...item}));
      const target = this.getRowByKey(key,newData);
      if (this.cacheOriginData[key]) {
        Object.assign(target,this.cacheOriginData[key]);
        delete this.cacheOriginData[key];
      }
      target.editable = false;
      this.setState({ data : newData});
      this.ClickedCancel = false;
    } 
    //添加-删除
    cut(key){
      const { data } = this.state;
      const { onChange } = this.props;
      const newData = data.filter(item => item.key !== key);
      this.setState({ data: newData });
      onChange(newData);
    }

    onSelectHospChange = (value) => {
      this.setState({ hospID: value },
        () => {
          this.handleQuery();
        });
    }

    render() {

      const { loading, data } = this.state;
      let tableHeight;
      if (data.length === 0) {
        tableHeight = 200;
      }else{
        tableHeight = "auto";
      }
      return (
          <Fragment>
            <div>
              <Select style={{ width: 300 }} defaultValue={user.hospID + ""} onChange={this.onSelectHospChange}>
                {
                  this.state.hospital.map((item) => {
                    return (
                      <Option key={item.id} value={item.id + ""} title={item.descriptsSPCode} >{item.descripts}</Option>
                    )
                  })
                }
              </Select>
            </div>
            <Table
              loading={loading}
              columns={this.columns}
              dataSource={data}
              pagination={false}
              rowClassName={record => (record.editable ? 'record' : '')}
              style={{height : tableHeight }}
            />
            <Button
              style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
              type="dashed"
              onClick={this.newMember}
              icon="plus"
            >新增配置
            </Button>
          </Fragment>
            );
    }
  }