/*
 * Creator:     ML
 * CreatDate:   2020-09-21
 * descripts：  录入诊断目录信息
 * */
import React from 'react';
import moment from 'moment';
import { Form, Row, Col, Input, Table, Select, Tree, Button, Modal, message, Divider, DatePicker, Icon, Card, Checkbox, Radio, Badge, Fragment, Pagination, Popconfirm } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';
import './css/OrderTemple.less';
import './css/ApplicationSetting.less';
import DiagnosticClassificDeatil from './DiagnosticClassificDeatil';

const { Search } = Input;

const formItemLayout = { // label 和input宽度
  labelCol: { span: 9 },
  wrapperCol: { span: 12 }
}

const formItemLayoutR = {
  labelCol: { span: 9 },
  wrapperCol: { span: 15 }
}
const FormItem = Form.Item;
const Option = Select.Option;
const DiagnosticClassificationMain = Form.create()(
    class DiagnosticClassificationMain extends React.Component {
      cacheOriginData = {};
      constructor(props) {
        super(props);
        this.state = {
          expandedKeys: [],
          selectedKeys: [],
          searchValue: '',
          autoExpandParent: true,
          threeData: [],
          record: {},
          baseParentType: [],
          inputValue: "",
          checked: true,//默认选择生效
          visible: false,//添加/修改分类设置弹窗显示
          isMod: -1,//是否点击编辑
          tipStatus: false,
          canAdd: false,
        }
      }

      componentDidMount = () => {
        this.handleQuery();
      }

      generateList = data => {
        let dataList = []
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          const { key } = node;
          dataList.push({ key, title: key });
          this.setState({
            dataList,
          })
          if (node.children) {
            this.generateList(node.children);
          }
        }
      };

      //获取左侧搜索输入框值
      changeInfo = (e) => {
        this.setState({
          searchCategoryName: e.target.value
        })
      }
      //回车查找分类设置数据
      handleQuery = () => {
        let data = {}
        data = {
          params: [{
            hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
            upDirectID: "",
            locID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : "",
            inputValue: this.state.inputValue && this.state.inputValue || ""
          }],
        }
        $http.post('urlS', this, {
          code: '03050253',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              this.setState({
                threeData: res.result.data,
              })
              if (res.result.data.length == 0) {
                this.setState({
                  tipStatus: true
                })
              } else {
                this.setState({
                  tipStatus: false
                })
              }
            } else {

            }
          }
        })
      }
      //调子组件
      onAttRef = (ref) => {
        this.childAtt = ref
      }
      //添加分类设置弹出
      openDocMes = () => {
        this.props.form.resetFields()
        // console.log("this.state.selectedKeys[0]", this.state.selectedKeys[0])
        this.setState({
          isMod: -1,
          visible: true
        }, () => {
          this.getParentSelect((this.state.selectedKeys && this.state.selectedKeys[0]) || "")
        })
      }
      //点击添加/修改分类设置弹窗确认按钮
      handleOk = (e) => {
        this.props.form.validateFields((err, values) => {
          if (!err) {
            let data = {}
            data = {
              params: [{
                ID: this.state.isMod == 1 ? (this.state.selectedKeys && this.state.selectedKeys[0]) : "",
                upDirectID: this.state.isMod == 1 ? this.state.upDirectID : values.upDirectID,
                userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                locID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).locID : "",
                hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                directENDesc: values.directENDesc,
                directDesc: values.directDesc,
                startDate: values.dateFrom ? moment(values.dateFrom).format('YYYY-MM-DD') : undefined,//生效日期
                stopDate: values.dateTo ? moment(values.dateTo).format('YYYY-MM-DD') : undefined,//失效日期
              }],
            }
            $http.post('urlS', this, {
              code: '03050254',
              data: data,
              success: function (res) {
                if (+res.errorCode === 0) {
                  if (this.state.isMod == 1) {
                    message.success("修改成功")
                    this.initData()
                  } else {
                    message.success("新建成功")
                    this.initData()
                    this.setState({
                      inputValue: ""
                    })
                  }
                  this.setState({
                    visible: false,
                  })
                  this.handleQuery()

                } else {

                }
              }
            })
          }
        })
      }
      //获取上级分类下拉框
      getParentSelect = (directID) => {
        let data = {}
        data = {
          params: [{
            directID: directID ? directID : "",
            hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
          }],
        }
        $http.post('urlS', this, {
          code: '03050259',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              this.setState({
                baseParentType: res.result,
              })
            }
          }
        })
      }
      //编辑分类
      handleEdit = (e, item, flag) => {
        if (e && e.stopPropagation) {
          e.stopPropagation();
        }
        // console.log(e)
        //编辑
        if (flag == 1) {
          this.getParentSelect(item.ID)
          this.props.form.resetFields()
          this.setState({
            record: item,
            isMod: 1,
            visible: true
          }, () => {
            this.props.form.setFieldsValue({
              directDesc: item.directDesc,
              directENDesc: item.directENDesc,
              upDirectID: item.upDirectID,
              dateFrom: item.startDate ? moment(item.startDate, "YYYY-MM-DD") : moment(),
              dateTo: item.stopDate ? moment(item.stopDate, "YYYY-MM-DD") : undefined,
            });
          })
        } else {
          //删除
          let datas = {}
          datas = {
            params: [{
              userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
              ID: item.ID,
            }],
          }
          $http.post('urlS', this, {
            code: '03050255',
            data: datas,
            success: function (res) {
              if (+res.errorCode === 0) {
                message.success("删除成功");
                this.handleAllClear()
              }
            }
          })
        }
      }
      getRightDeatil = (HBid) => {
        let data = {}
        data = {
          params: [{
            searchCode: "",
            HBid: HBid,
          }],
        }
        $http.post('urlS', this, {
          code: '03010010',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0 && res.data) {
              this.setState({
                rightData: res.data
              })

            }
          }
        })
      }
      //初始化信息
      initData = () => {
        this.setState({
          isMod: -1,
          ordShow: false,
          tempChildDis: false
        })

      }
      //点击添加/修改分类设置弹窗取消按钮
      handleCancel = () => {
        this.setState({
          visible: false,
          record: {}
        })
        this.initData()
      }
      findApp = () => {
        this.handleQuery()
      }
      //判断某个字符出现几次 aStr为某字符串 aChar为某字符
      getStrCount = (aStr, aChar) => {
        var regex = new RegExp(aChar, 'g'); // 使用g表示整个字符串都要匹配
        var result = aStr.match(regex);
        var count = !result ? 0 : result.length;
        return count;
      }
      //展开目录
      onExpand = expandedKeys => {
        this.setState({
          expandedKeys,
          autoExpandParent: false,
        });
      };
      //选中目录
      handleSelect = (selectedKeys, e) => {
        // console.log("selectedKeys---选中",selectedKeys,"getStrCount",this.getStrCount(e.node.props.selectKey,"-"),"e.node.props.selectKey",e.node.props.selectKey)
        this.setState({
          selectedKeys,
          upDirectID: e.node.props.upDirectID,
          title: e.node.props.title,
          upDirectDesc: e.node.props.upDirectDesc,
          autoExpandParent: false,
        }, () => {
          //取消选中
          if (selectedKeys && selectedKeys[0] == undefined) {
            this.childAtt.clearInfo("2")
            this.childAtt.getInfo({}, "")
            this.setState({
              canAdd: false
            })
          } else {
            //限制添加2层 选中时
            if (this.getStrCount(e.node.props.selectKey, "-") == 2) {
              this.setState({
                canAdd: true
              })
            } else {
              this.setState({
                canAdd: false
              })
            }
            this.handleInfo(this.state.selectedKeys && this.state.selectedKeys[0])
          }
        });
      }
      handleInfo = (directID) => {
        let data = {}
        data = {
          params: [{
            directID: directID && directID || "",
          }],
        }
        $http.post('urlS', this, {
          code: '03050256',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0 && res.result.data) {
              this.childAtt.getInfo({}, directID && directID || "", res.result.data)
            }
          }
        })
      }
      // generateData = (_level, _preKey, _tns) => {
      //   const preKey = _preKey || '0';
      //   const tns = _tns || this.state.threeData;

      //   const children = [];
      //   for (let i = 0; i < 3; i++) {
      //     const key = `${preKey}-${i}`;
      //     tns.push({ title: key, key });
      //     if (i < 3) {
      //       children.push(key);
      //     }
      //   }
      //   if (_level < 0) {
      //     return tns;
      //   }
      //   const level = _level - 1;
      //   children.forEach((key, index) => {
      //     tns[index].children = [];
      //     return this.generateData(level, key, tns[index].children);
      //   });
      // };

      // getParentKey = (key, tree) => {
      //   let parentKey;
      //   for (let i = 0; i < tree.length; i++) {
      //     const node = tree[i];
      //     if (node.children) {
      //       if (node.children.some(item => item.key === key)) {
      //         parentKey = node.key;
      //       } else if (this.getParentKey(key, node.children)) {
      //         parentKey = this.getParentKey(key, node.children);
      //       }
      //     }
      //   }
      //   return parentKey;
      // };
      //搜索 框 值
      handleInt = (e) => {
        if (e) {
          this.setState({
            inputValue: e.target.value
          })
        } else {
          this.setState({
            inputValue: ""
          })
        }
      }
      //回车搜索 清除
      handleSearch = () => {
        this.setState({
          selectedKeys: [],
          autoExpandParent: true,
          threeData: [],
          tipStatus: true
        }, () => {
          this.handleRest()
        })

      }
      handleRest = () => {
        this.childAtt.clearInfo("2")
        this.childAtt.getInfo({}, "")
        this.handleQuery()
      }
      //状态清空
      handleAllClear = () => {
        this.setState({
          title: "",
          selectedKeys: [],
          threeData: [],
          tipStatus: true
        }, () => {
          this.handleRest()
        })

      }
      newAdd = () => {
        this.setState({
          rowIds: "",
        });
        this.childAtt.clearInfo()
      }
      render() {
        const { getFieldDecorator } = this.props.form;
        const { searchValue, expandedKeys, autoExpandParent, baseParentType, threeData, record, } = this.state;
        // gData = threeData
        const loop = data =>
            data.map(item => {
              const index = item.title.indexOf(searchValue);
              const beforeStr = item.title.substr(0, index);
              const afterStr = item.title.substr(index + searchValue.length);
              const title =
                  index > -1 ? (
                      <span>
                {beforeStr}
                        <span className="site-tree-search-value">{searchValue}</span>
                        {afterStr}
                        {/*<span className="edit-span">*/}
                        {/*  <span style={{ color: "#1890ff", marginRight: "8px" }} onClick={(event,) => this.handleEdit(event, item, "1")}>编辑</span>*/}
                        {/*  <Popconfirm title="是否要删除此分类" onConfirm={(e) => this.handleEdit(e, item, "2")}>*/}
                        {/*    <span style={{ color: "red" }}>删除</span>*/}
                        {/*  </Popconfirm>*/}
                        {/*</span>*/}
              </span>
                  ) : (
                      <p>
                        <span>{item.title}</span>
                        {/*<span className="edit-span">*/}
                        {/*  <span style={{ color: "#1890ff", marginRight: "8px" }} onClick={(event,) => this.handleEdit(event, item, "1")}>编辑</span>*/}
                        {/*  <Divider type="vertical" />*/}
                        {/*  <Popconfirm title="是否要删除此分类" onConfirm={(e) => this.handleEdit(e, item, "2")}>*/}
                        {/*    <span style={{ color: "red" }}>删除</span>*/}
                        {/*  </Popconfirm>*/}
                        {/*</span>*/}
                      </p>
                  );
              if (item.children) {
                // return (
                //   <TreeNode key={item.key} title={title}>
                //     {loop(item.children)}
                //   </TreeNode>
                // );
                return {
                  title,
                  key: item.ID,
                  upDirectID: item.upDirectID,
                  selectKey: item.key,
                  upDirectDesc: item.upDirectDesc,
                  children: loop(item.children),
                };
              }
              // return <TreeNode key={item.key} title={title} />;
              return {
                title,
                key: item.ID,
                upDirectID: item.upDirectID,
                selectKey: item.key,
                upDirectDesc: item.upDirectDesc,
              };
            });
        let parentType = []
        baseParentType && baseParentType.map(item => {
          parentType.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
        })
        return (
            <div>
              <Row gutter={60} className="applicationDom diagDom" style={{ marginRight: "0" }}>
                <Col span={6} style={{ paddingRight: "0" }}>
                  <Card title="诊断分类" bordered={false} style={{ marginRight: "4px", }}>
                    {/*<Row>*/}
                    {/*  <Col span={2} style={{ position: "absolute", right: "31px", top: "-41px" }}>*/}
                    {/*    <FormItem >*/}
                    {/*      {getFieldDecorator('addCategories', {*/}
                    {/*        initialValue: undefined,*/}
                    {/*        rules: [{ required: false, message: '' }],*/}
                    {/*      })(*/}
                    {/*        <Button*/}
                    {/*          type="primary"*/}
                    {/*          style={{ height: "26px" }}*/}
                    {/*          disabled={this.state.canAdd}*/}
                    {/*          onClick={this.openDocMes}>+分类</Button>*/}
                    {/*      )}*/}
                    {/*    </FormItem>*/}
                    {/*  </Col>*/}
                    {/*</Row>*/}
                    {/*<Row>*/}
                    {/*  <p style={{ margin: "4px 0", color: "#1890ff" }}>说明：点击“+分类”,可直接添加一级目录；选择某个分类后，点击“+分类”添加子类，至多2层</p>*/}
                    {/*</Row>*/}
                    <Row>
                    </Row>
                    {/*<Search allowClear style={{ marginBottom: 8 }} placeholder="输入分类名称回车搜索" value={this.state.inputValue} onChange={this.handleInt} onSearch={this.handleSearch} />*/}

                    {
                      this.state.tipStatus ?
                          <Row style={{ textAlign: "center" }}>
                            暂无数据
                          </Row> : <Tree
                              onExpand={this.onExpand}
                              expandedKeys={expandedKeys}
                              autoExpandParent={autoExpandParent}
                              onSelect={this.handleSelect}
                              treeData={loop(this.state.threeData)}
                          />
                    }
                    <div className="ordTempDateil">
                      <Modal
                          key='2'
                          width='416px'
                          visible={this.state.visible}
                          title={this.state.isMod == 1 ? "编辑分类" : "添加分类"}
                          onOk={this.handleOk}
                          onCancel={this.handleCancel}
                          footer={[
                            <Button key="submitc" type="primary" onClick={this.handleCancel}>取消</Button>,
                            <Button key="submits" type="primary" onClick={this.handleOk}>确定</Button>,
                          ]}>
                        <div>
                          <Form>
                            <Row gutter={60}>
                              <Col span={24}>
                                <FormItem label='目录描述' {...formItemLayout}>
                                  {getFieldDecorator('directDesc', {
                                    initialValue: record && record.directDesc || undefined,
                                    rules: [{ required: true, message: '请输入描述' }],
                                  })(
                                      <Input placeholder="不能超过10个字" maxLength={10} style={{ width: "100%" }} />
                                  )}
                                </FormItem>
                              </Col>
                            </Row>
                            <Row gutter={60}>
                              <Col span={24}>
                                <FormItem label='描述英文'  {...formItemLayout}>
                                  {getFieldDecorator('directENDesc', {
                                    initialValue: record && record.directENDesc || undefined,
                                    rules: [{ required: false, message: '' }],
                                  })(
                                      <Input />
                                  )}
                                </FormItem>
                              </Col>
                            </Row>
                            <Row gutter={60}>
                              <Col span={24}>
                                <FormItem label='上级分类'  {...formItemLayout}>
                                  {getFieldDecorator('upDirectID', {
                                    initialValue: undefined,
                                    rules: [{ required: this.state.isMod == 1 || (this.state.selectedKeys && this.state.selectedKeys[0] == undefined) ? false : true, message: '请选择上级分类' }],
                                  })(
                                      <Select style={{ width: "100%" }} disabled={this.state.isMod == 1 || (this.state.selectedKeys && this.state.selectedKeys[0] == undefined)}>
                                        {parentType}
                                      </Select>
                                  )}
                                </FormItem>
                              </Col>
                            </Row>
                            <Row gutter={60}>
                              <Col span={24} >
                                <FormItem label='生效日期' {...formItemLayout}>
                                  {getFieldDecorator('dateFrom', {
                                    initialValue: record.startDate ? moment(record.startDate, "YYYY-MM-DD") : moment(),
                                    rules: [{ required: true, message: '请选择生效日期' }],
                                  })(
                                      <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                        return curDate && curDate > moment().endOf('day');
                                      }} />
                                  )}
                                </FormItem>
                              </Col>
                            </Row>
                            <Row gutter={60}>
                              <Col span={24} >
                                <FormItem label='失效日期' {...formItemLayout}>
                                  {getFieldDecorator('dateTo', {
                                    initialValue: record.stopDate ? moment(record.stopDate, "YYYY-MM-DD") : undefined,
                                    rules: [{ required: false, message: '' }],
                                  })(
                                      <DatePicker style={{ width: '100%' }} />
                                  )}
                                </FormItem>
                              </Col>
                            </Row>
                            <Row>
                            </Row>
                          </Form>
                        </div>
                      </Modal>
                    </div>

                  </Card>
                </Col>
                <Col span={18} className="right-dom" style={{ paddingLeft: "6px", paddingRight: "0" }}>
                  <Card title={this.state.title && this.state.title ? this.state.title : "请选择左侧目录"} bordered={false} className="moreInfoCard" style={{ paddingRight: "0" }}>
                    {/*<p className="titleDom"> 录入诊断信息</p>*/}
                    <div>
                      <DiagnosticClassificDeatil localeProvider={this.state.localeProvider} newAdd={this.newAdd} handleInfo={this.handleInfo} onAttRef={this.onAttRef} handleQuery={this.handleQuery}></DiagnosticClassificDeatil>
                    </div>
                  </Card>
                </Col>
              </Row>
            </div>
        )
      }
    })
export default DiagnosticClassificationMain
