import React from 'react'
import { connect } from 'dva'
import { Row, Col, Button, Collapse, Progress, Tabs, Icon, Popover, Input, message, Spin } from 'antd'
import { initFilter, extendRule, extendInclude, initQueryFilter } from "../../../../utils/common"
import styles from './index.css'
import ListTablePageBase from '../../../Table/ListTablePageBase'
import storage from "../../../../utils/storage"
import Edit from '../../../Edit/Edit'
import { Search } from '@woowalker/feui'
import ChartComponent from '../../../Chart'
import ProductRecord from './ProductRecord'
const Panel = Collapse.Panel
const TabPane = Tabs.TabPane

class ProductOrderQuery extends React.Component {
  constructor (props) {
    super(props)
    this.orgId = storage('lacal').getItem('webOrgId').val
    this.state = {
      visible: false,
      PdtData: {},
      currentPdtDetail: {},
      param: {},
      loadFunc: {},            //listbase传出的查询方法
      tableList: [],
      tableData: {},
      workReord: {},
      query: {},
      processRouting: 100,
      processPercent: 0,
      processDetails: [],
      PO: '',
      searchNo: '',
      inputNO: '',
      loading: false,
      tabActiveKey: ""
    }
  };

  componentDidMount () {
    this.loadData()
  };

  loadData = () => {
    const { formId, formCode } = this.props
    const orgId = this.props.login.OrgId
    // const OJson = initFilter(orgId);
    // if (formId) {
    //   extendRule(OJson, 'ID', 1, formId);
    // }
    // else {
    //   extendRule(OJson, 'CODE', 1, formCode);
    // }
    const OJson = { 'Key': formId || formCode, 'orgid': orgId }
    //extendRule(OJson, 'CODE', 1, formCode);
    this.props.dispatch({
      type: 'app/getFormByRedis',
      payload: OJson,
      onComplete: (ret) => {
        if (ret) {
          this.setState({
            formData: ret
          }, () => {
            let val = initQueryFilter(orgId, 1, 100, "NUM", 0)
            extendRule(val, "PAGE_FORM_ID", 1, ret.ID)
            extendRule(val, "PARENT_ID", 1, null)
            this.props.dispatch({
              type: 'listPage/getTableListData',
              payload: val,
              onComplete: (ret) => {
                if (ret !== null) {
                  this.setState({
                    tableList: ret,
                  }, () => {
                    if (this.props.SearchNo) {
                      this.setState({
                        searchNo: this.props.SearchNo,
                      })
                      //let data = { data: [this.props.SearchNo] };
                      this.onSelectStage(this.props.SearchNo)
                    }
                  })
                }
              }
            })
          })
        }
      }
    })
  };

  getRecordView = (pdtId, page, limit) => {
    let json1 = initQueryFilter(this.props.login.OrgId, page, limit, "CREATE_TIME", 1)
    extendRule(json1, "PDT_ORDER_ID", 1, pdtId)
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'MM/WorkRecord/OrderPaged',
      payload: json1,
      onlyData: false,
      onComplete: (ret) => {
        if (ret.Data instanceof Array) {
          this.setState(prevState => {
            return {
              workReord: {
                ...ret,
                Data: (prevState.workReord.Data || []).concat(ret.Data)
              }
            }
          })
        }
      }
    })
  };

  loadFun = (name) => {
    if (this.state.loadFunc && this.state.loadFunc[name]) {
      this.state.loadFunc[name]({
        extendParam: {
          PageIndex: 1,
          Start: 0
        }
      })
    }
  };

  getSearchComponent = (code) => {
    return <Search formId={this.props.formId} formCode={this.props.formCode} onSearch={(value) => this.handleSearch(value, code)} code={code} />
  };

  handleSearch = (value, code) => {
    this.setState({
      searchRules: value
    }, () => {
      this.loadFun(code)
    })
  };

  handleCloseModal = () => {
    this.setState({
      visible: false,
      currentPdtDetail: {}
    })
  };

  handleProcedureDetail = (item, isShow) => {
    this.setState({
      visible: isShow,
      currentPdtDetail: item
    })
  };

  handleLoadParam = ({ pageCode }) => {
    //this.searchFormRef.handleSearch();
    const param = this.state['param']
    let tmpParam = param ? param : {}
    let tmp = tmpParam[pageCode] ? tmpParam[pageCode] : {}
    //生产记录
    if (pageCode == "workrecord" || pageCode == "work" || pageCode == "qc"
      || pageCode == "bad" || pageCode == "sop" || pageCode == "bom" || pageCode == "batch"
      || pageCode == "snlist" || pageCode == "job") {
      let rule = [
        {
          field: "PDT_ORDER_ID",
          operator: 1,
          value: this.state.PdtData.ID
        }
      ]
      return this.setQueryRules(tmp, rule)
    }
    //维修
    else if (pageCode == "repair") {
      let rule = [
        {
          field: "Nav_Bad.PDT_ORDER_ID",
          operator: 1,
          value: this.state.PdtData.ID
        }
      ]
      return this.setQueryRules(tmp, rule)
    }
    //订单工艺
    else if (pageCode == "process") {
      let rule = [
        {
          field: "PDT_PROCESS_ID",
          operator: 1,
          value: this.state.PdtData.PDT_PROCESS_ID
        }
      ]
      return this.setQueryRules(tmp, rule)
    }

    else if (pageCode == "retwork") {
      let rule = [
        {
          field: "PARENT_ID",
          operator: 1,
          value: this.state.PdtData.ID
        },
        {
          field: "PDT_ORDER_TYPE",
          operator: 1,
          value: 1
        }
      ]
      return this.setQueryRules(tmp, rule)
    }
    return ''
  };

  setRules = (obj, rule) => {
    if (obj) {
      if (obj.data) {
        obj.data["rules"] = [...obj.data["rules"], ...rule]
      } else {
        obj["data"] = {
          rules: rule
        }
      }
    } else {
      obj = {
        data: {
          rules: rule,
        }
      }
    }
  };

  setQueryRules = (pageCode, rule) => {
    let param = this.state['param']
    let tmp = param[pageCode]
    const rules = this.state.searchRules && this.state.searchRules.rules ? this.state.searchRules.rules : []
    const groups = this.state.searchRules && this.state.searchRules.groups ? this.state.searchRules.groups : []
    if (tmp) {
      if (tmp.data) {
        if (rules) {
          tmp.data["rules"] = [...tmp.data["rules"], ...rules]
        }
        if (groups) {
          tmp.data["groups"] = [...tmp.data["groups"], ...groups]
        }
      } else {
        if (rules) {
          tmp["data"] = {
            rules: [...rules],
            groups: [...groups],
          }
        }
      }
    } else {
      if (rules) {
        tmp = {
          data: {
            rules: [...rules],
            groups: [...groups],
          }
        }
      }
      else {
        tmp = {
          data: {
          }
        }
      }

      tmp.data["rules"] = [...tmp.data["rules"], ...rule]
    }
    return tmp
  };

  ActionloadFun = (name) => {
    if (this.state.loadFunc && this.state.loadFunc[name]) {
      this.state.loadFunc[name]({
        extendParam: {
          PageIndex: 1,
          Start: 0
        }
      })
    }
  };

  handleLoadDataFunc = ({ loadFunc, pageCode }) => {
    const d = { ...this.state.loadFunc }
    d[pageCode] = loadFunc
    this.setState({
      loadFunc: d,
    })
  };

  getTableData = (tableData, tableCode) => {
    let tmp = { ...this.state.tableData }
    tmp[tableCode] = tableData
    this.setState({
      tableData: tmp
    })
  };

  getListComponent = (code) => {
    let tableIndex = this.props.tableIndex
    if (!tableIndex) {
      tableIndex = 1
    }

    return this.state.tableList.map(item => {
      let query = false
      if (this.state.PdtData && this.state.PdtData.ID) {
        query = true
      }
      if (item.CODE === code) {
        return <div>
          <div style={{ marginBottom: 15 }}>
            {this.getSearchComponent(code)}
          </div>
          <ListTablePageBase
            key={item.ID}
            tableId={item.ID}
            formData={this.state.formData}
            formCode={this.state.formData ? this.state.formData.CODE : ''}
            onRegLoadDataFunc={this.handleLoadDataFunc}
            onLoadParam={this.handleLoadParam}
            formId={this.props.formId}
            SetRowClass={this.setRowClass}
            onClickRow={this.handleOrderRowClick}
            query={query}
            onTableData={this.onOrderTableData} />
        </div>
      } else {
        return null
      }
    })
  };

  onChange = (value) => {
    this.setState({
      inputNO: value
    })
  };

  sendCheck = () => {
    const json = initFilter(this.orgId, this.state.PdtData.PDT_CODE)
    //json["Parameter1"]=
    json["Parameter2"] = this.props.login.login.userId
    this.props.dispatch({
      //type: "WOOrderQuery/getOrderList",
      type: 'app/getDataByPost',
      url: 'QC/Order/FQC',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re.IsSuccessful && re.Data) {
          this.onSelectStage([this.state.PdtData.PDT_CODE])
        }
      }
    })
  };

  sendQaCheck = () => {
    const json = initFilter(this.orgId, this.state.PdtData.PDT_CODE)
    //json["Parameter1"]=
    json["Parameter2"] = this.props.login.login.userId
    this.props.dispatch({
      //type: "WOOrderQuery/getOrderList",
      type: 'app/getDataByPost',
      url: 'QC/Order/Qa',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re.IsSuccessful && re.Data) {
          this.onSelectStage([this.state.PdtData.PDT_CODE])
        }
      }
    })
  };

  onSelectStage = (data) => { // 选择生产订单
    if (!data) {
      data = this.state.searchNo
    }
    if (data) {
      this.setState({
        workReord: {},
        inputNO: '',
        loading: true
      })

      const json = initFilter(this.orgId, '', 'PDT_CODE', 0, 1)
      extendRule(json, 'PDT_CODE', 1, data)
      //extendInclude(json, "Nav_PdtProcess.Nav_Details");
      extendInclude(json, "Nav_Product")
      extendInclude(json, "Nav_PdtSaleOrders.Nav_SoOrderDetail.Nav_Order")
      this.setState(prevState => {
        if (JSON.stringify(prevState.workReord) === "{}") {
          this.props.dispatch({
            //type: "WOOrderQuery/getOrderList",
            type: 'app/getDataByPost',
            url: 'WO/PDTOrder/Get',
            payload: json,
            onlyData: false,
            onComplete: (re) => {
              if (re.IsSuccessful && re.Data) {
                let res = re.Data
                this.setState({
                  searchNo: res.PDT_CODE
                })
                //获取第一层工艺路线
                const json1 = initFilter(this.orgId, '', 'NUM', 0, 1)
                extendRule(json1, 'PDT_PROCESS_ID', 1, res.PDT_PROCESS_ID)
                extendRule(json1, 'PARENT_ID', 1, '')
                this.props.dispatch({
                  type: 'app/getDataByPost',
                  url: 'WO/PDTProcessDetail/OrderEntities',
                  payload: json1,
                  onComplete: (ret) => {

                    this.setState({
                      processDetails: ret ? ret : [],
                    })
                    if (ret) {
                      //计算工序直通率
                      let tmpRouting = 1
                      //完工百分比
                      let processPercents = 0
                      let totalTime = 0
                      let spentTime = 0
                      ret.forEach((n) => {
                        totalTime += n.QTY * n.STANDARD_TIME
                        if (n.TOTAL_BOOK_QTY != 0) {
                          spentTime += n.FINISH_QTY * n.STANDARD_TIME
                          tmpRouting = tmpRouting * (n.TOTAL_BOOK_QTY - n.TOTAL_BAD_QTY) / n.TOTAL_BOOK_QTY
                        }
                      })
                      tmpRouting = (tmpRouting * 100).toFixed(1)
                      //有配置标准工时
                      if (totalTime > 0) {
                        processPercents = (100 * spentTime / totalTime).toFixed(1)
                      }

                      else//没配置
                      {
                        processPercents = (res.FINISH_QTY / res.QTY * 100).toFixed(1)
                      }

                      this.setState({
                        processRouting: tmpRouting,
                        processPercent: processPercents
                      })
                      //计算完工%
                    }
                  }
                })

                let initParam = {}
                let workRecordFilter = initFilter(this.orgId, '', 'CREATE_TIME', 1)
                extendInclude(workRecordFilter, "PDT_ORDER_ID", 1, res.ID)
                initParam["workrecord"] = workRecordFilter
                let po = ''
                let poarray = []
                if (res.Nav_PdtSaleOrders) {
                  res.Nav_PdtSaleOrders.forEach((n) => {
                    if (n.Nav_SoOrderDetail && n.Nav_SoOrderDetail.Nav_Order && poarray.indexOf(n.Nav_SoOrderDetail.Nav_Order.CODE) < 0) {
                      po += n.Nav_SoOrderDetail.Nav_Order.CODE + ","
                      poarray.push(n.Nav_SoOrderDetail.Nav_Order.CODE)
                    }
                  })
                }
                this.setState({
                  PdtData: res || {},
                  param: initParam,
                  PO: po,
                  loading: false
                }, () => {
                  message.success('查询成功')
                })
                //查询列表数据
                this.getRecordView(res.ID, 1, 10)
                this.ActionloadFun("workrecord")
                this.ActionloadFun("work")
                this.ActionloadFun("job")
                this.ActionloadFun("bom")
                this.ActionloadFun("snlist")
                this.ActionloadFun("process")
                this.ActionloadFun("qc")
                this.ActionloadFun("bad")
                this.ActionloadFun("retwork")
                this.ActionloadFun("sop")
                this.ActionloadFun("batch")

              } else {
                this.setState({
                  searchNo: '',
                  loading: false
                }, () => {
                  message.error('不存在此生产订单')
                })
              }

            }
          })
        }
      })
    }
  };

  render () {
    const rule = [
      {
        field: "Nav_Bad.PDT_ORDER_ID",
        operator: 1,
        value: this.state.PdtData.ID
      }
    ]
    let tmp = { data: {} }
    tmp.data["rules"] = [...rule]
    const { PdtData, currentPdtDetail, processDetails, workReord, tabActiveKey } = this.state
    const Nav_Details = processDetails ? processDetails : []
    const tabListNoTitle = [{
      key: 'recordView',
      tab: <span><Icon type="bars" />生产履历</span>,
      content: <ProductRecord workReord={workReord} PdtData={PdtData} getRecordView={this.getRecordView} />,
    }, {
      key: 'snlist',
      tab: <span><Icon type="book" />在线SN</span>,
      content: this.getListComponent('snlist')
    }, {
      key: 'workrecord',
      tab: <span><Icon type="laptop" />生产记录</span>,
      content: this.getListComponent('workrecord')
    }, {
      key: 'process',
      tab: <span><Icon type="setting" />订单工艺</span>,
      content: this.getListComponent('process')
    },
    {
      key: 'job',
      tab: <span><Icon type="idcard" />工单列表</span>,
      content: this.getListComponent('job')
    },
    {
      key: 'work',
      tab: <span><Icon type="idcard" />派工单</span>,
      content: this.getListComponent('work')
    },
    {
      key: 'bom',
      tab: <span><Icon type="layout" />订单物料</span>,
      content: this.getListComponent('bom')
    },
    {
      key: 'batch',
      tab: <span><Icon type="barcode" />批次溯源</span>,
      content: this.getListComponent('batch')
    },
    {
      key: 'sop',
      tab: <span><Icon type="picture" />SOP列表</span>,
      content: this.getListComponent('sop')
    }, {
      key: 'qc',
      tab: <span><Icon type="check-circle-o" />检验记录</span>,
      content: this.getListComponent('qc')
    }, {
      key: 'bad',
      tab: <span><Icon type="tool" />不良记录</span>,
      content: this.getListComponent('bad')
    }, {
      key: 'retwork',
      tab: <span><Icon type="retweet" />返工订单</span>,
      content: this.getListComponent('retwork')
    }]

    const popContext = (currentPdtDetail) => {
      return (<div style={{ width: 600 }}>
        <Row gutter={16}>
          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>工序：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.NAME}</span></Col>
            </Row>
          </Col>
          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>计划数：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.PLAN_QTY}</span></Col>
            </Row>
          </Col>

          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>计划开始：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.PLAN_START_TIME}</span></Col>
            </Row>
          </Col>
          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>计划完成：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.PLAN_END_TIME}</span></Col>
            </Row>
          </Col>

          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>报工开始：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.START_TIME}</span></Col>
            </Row>
          </Col>
          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>报工截止：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.END_TIME}</span></Col>
            </Row>
          </Col>
          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>完成数：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.FINISH_QTY}</span></Col>
            </Row>
          </Col>
          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>当前不良数：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.BAD_QTY}</span></Col>
            </Row>
          </Col>
          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>累计不良数：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.TOTAL_BAD_QTY}</span></Col>
            </Row>
          </Col>
          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>报废数：</label></Col>
              <Col span={16}><span className={styles.detailSpan}>{currentPdtDetail.SCRAP_QTY}</span></Col>
            </Row>
          </Col>
          <Col span={12}>
            <Row gutter={16}>
              <Col span={8} className={styles.detailName}><label>通过率：</label></Col>
              <Col span={16}>
                <span className={styles.detailSpan}>
                  {
                    currentPdtDetail.TOTAL_BOOK_QTY !== 0
                      ? ((currentPdtDetail.TOTAL_BOOK_QTY - currentPdtDetail.TOTAL_BAD_QTY) / currentPdtDetail.TOTAL_BOOK_QTY * 100).toFixed(2) + '%'
                      : null
                  }
                </span>
              </Col>
            </Row>
          </Col>
        </Row>
      </div>)
    }

    return (

      <Spin spinning={this.state.loading} delay={500}>

        <div>
          <Row gutter={16} style={{ lineHeight: "32px" }}>
            <Col span={3} style={{ textAlign: "right", fontSize: 16 }}>生产订单：</Col>
            <Col span={10}>
              {/* <DropDownPagination inputDataApi={'WO/PDTOrder/OrderPaged'}
            inputLabelField={''}
            inputShowField={'PDT_CODE'}
            inputFilterField={'PDT_CODE'}
            value={this.state.onSelectStageName}
            onSelect={this.onSelectStage}
            onChangeHandle={this.onChange}
            inpuNavField={'PDT_CODE'} /> */}
              <Input
                placeholder="请输入或扫描生产订单"
                //size="large"
                // eslint-disable-next-line no-return-assign
                ref={e => (this.refInput = e)}
                value={this.state.inputNO}
                onChange={e => this.onChange(e.target.value)}
                onPressEnter={e => this.onSelectStage(e.target.value)}
              />

            </Col>
            <Col>
              <Button
                //size="large"
                type="primary"
                style={{ marginLeft: 10 }}
                onClick={() => this.onSelectStage(this.state.inputNO)}
              > 搜索</Button>
            </Col>
          </Row>
          <div style={{ marginTop: 16 }}>
            <Collapse defaultActiveKey={['1', '2', '3', '4']}>
              <Panel header="基础信息" key="3">
                <Edit id={this.state.PdtData.ID} formCode={'WO015'} data={{ isShow: true }} ></Edit>
              </Panel>
              <Panel header="订单进度" key="1">
                <Row gutter={24}>
                  {
                    PdtData
                      ? <div>
                        <Col key={1} span={8}>
                          <div className={styles.procedureItem}>
                            <Progress percent={Number(this.state.processPercent)} /> {/*status={(this.state.processPercent>0&&this.state.processPercent<100)?'active':''} />*/}
                            <div>{'生产'}</div>
                          </div>
                        </Col> <Col key={2} span={8}>
                          <div className={styles.procedureItem}>
                            <Progress percent={+(PdtData.FINISH_QTY / PdtData.QTY * 100).toFixed(1)} /> {/*status={(PdtData.FINISH_QTY>0&&PdtData.FINISH_QTY<PdtData.QTY)?'active':''}/>*/}
                            <div>{'检验'}</div>
                          </div>
                        </Col> <Col key={3} span={8}>
                          <div className={styles.procedureItem}>
                            <Progress percent={+(PdtData.STORAGEED_QTY / PdtData.QTY * 100).toFixed(1)} /> {/*status={(PdtData.STORAGEED_QTY>0&&PdtData.STORAGEED_QTY<PdtData.QTY)?'active':''} />*/}
                            <div>{'入库'}</div>
                          </div>
                        </Col>
                      </div>
                      : <div className={styles.emptyProcedureData}>暂无数据</div>
                  }
                </Row>
              </Panel>
              <Panel header="生产进度" key="2">
                <Row gutter={16}>
                  {
                    Nav_Details.length > 0
                      ? Nav_Details.map(item => {
                        return <Col key={item.ID} xs={2} sm={4}>
                          <Popover placement="topLeft" content={popContext(item)} title={item.NAME} arrowPointAtCenter>
                            <div onClick={() => this.handleProcedureDetail(item, true)} className={styles.procedureItem}>
                              <Progress type="circle" width={80} percent={+(item.FINISH_QTY / item.QTY * 100).toFixed(1)} />
                              <div>{item.NAME}</div>
                            </div> </Popover>
                        </Col>
                      })
                      : <div className={styles.emptyProcedureData}>暂无数据</div>
                  }
                </Row>
              </Panel>
              <Panel header="生产信息" key="4">
                <Tabs onChange={activeKey => this.setState({ tabActiveKey: activeKey })}>
                  {
                    tabListNoTitle.map(item => <TabPane tab={item.tab} key={item.key}>
                      <div style={{ overflowX: "auto" }}>
                        {item.key === tabActiveKey ? item.content : tabListNoTitle[0].content}
                      </div>
                    </TabPane>)
                  }
                </Tabs>
              </Panel>
            </Collapse>
          </div>
          <div>
            <ChartComponent formCode={'PF016'} data={tmp.data}>  </ChartComponent>

          </div>
        </div>
      </Spin>
    )
  }
}
export default connect(({ login }) => ({ login }))(ProductOrderQuery)
