<template>
  <div class="diaClass">
    <!--		工作流引用  显示表单-->
    <!--		{{workflow.workId}}-->

    <el-card :body-style="cardBodyStyle">
      <el-divider content-position="left">
        <div style="color: #409EFF">结算信息</div>
      </el-divider>
      <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
        <el-row>
          <el-col :span="6">
            <el-form-item label="结算单号" prop="invNo" style="width: 100%">
              <el-input v-model="form.invNo" disabled>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算日期" prop="invDt" style="width: 100%">
              <el-date-picker
                  disabled
                  style="width: 100%"
                  v-model="form.invDt"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="申请日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同编号" prop="contrNo" style="width: 100%">
              <el-input v-model="form.contrNo" readonly>
                <!--                  <template #append>-->
                <!--                    <el-button :icon="Search" @click="dialogHt()"/>-->
                <!--                  </template>-->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="对方合同编号" prop="khContrNo">
              <el-input v-model="form.khContrNo" readonly>

              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户名称" prop="tradePartnerName">
              <el-input v-model="form.tradePartnerName" readonly>

              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="定价方式" prop="priceDcnMth">
              <el-select v-model="form.priceDcnMth" placeholder="请选择" clearable style="" disabled>
                <el-option v-for="item in dictList.PRICE_DCN_MTH" :key="item.dicCode" :label="item.dicName"
                           :value="item.dicCode"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="税率" prop="taxRate">
              <el-input v-model="form.taxRate" readonly>

              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="结算类型" prop="payMth">
              <el-select v-model="form.payMth" placeholder="请选择" clearable style="" disabled>
                <el-option v-for="item in dictList.COM_PAY_MTH" :key="item.dicCode" :label="item.dicName"
                           :value="item.dicCode"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="结算重量" prop="qty">
              <el-input v-model="form.qty" readonly>

              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算金额" prop="invAmt">
              <el-input v-model="form.invAmt" readonly>

              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算标识" prop="invFlag">
              <el-select v-model="form.invFlag" placeholder="请选择" clearable style="" disabled>
                <el-option v-for="item in dictList.INV_FLAG" :key="item.dicCode" :label="item.dicName"
                           :value="item.dicCode"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="打包号" prop="tostoHeaderNo">
              <el-input v-model="form.tostoHeaderNo"  style="" readonly>
              </el-input>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="开票说明">
              <el-input
                  readonly
                  v-model="form.invDesc"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  placeholder=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                  readonly
                  v-model="form.remark"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  placeholder=""
              />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-divider content-position="left">
        <div style="display: flex; text-align: center;align-items: center">
            <span style="color: #409EFF;">
              结算标准
            </span>

          <el-tooltip
              class="box-item"
              effect="dark"
              content="结算标准，用以生成结算单价"
              placement="top"
          >
            <el-icon style="color: #a5a5a5;">
              <InfoFilled/>
            </el-icon>
          </el-tooltip>

        </div>
      </el-divider>
      <div style="display: flex">
        <el-table :data="tableDataSettlement" border highlight-current-row
                  @selection-change="handleSelectionChangeSettlement"
                  height="245">
          <!--            <el-table-column type="selection" fixed></el-table-column>-->
          <el-table-column type="index" label="序号" align="center" width="60">
            <template #default="scope">
              <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="true" prop="settleNo" label="结算项目编码" min-width="100" header-align="center"
                           align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="settleItem" label="结算项目" min-width="100" header-align="center"
                           align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="settleValueTo" label="结算项目上限" min-width="100" header-align="center"
                           align="right" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="settleValueFrom" label="结算项目下限" min-width="100"
                           header-align="center"
                           align="right" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="referenceValue" label="基准值" min-width="100" header-align="center"
                           align="right" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="settleSpan" label="结算项目跨度" min-width="100" header-align="center"
                           align="right" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="true" prop="settleDiffer" label="结算差额" min-width="100" header-align="center"
                           align="right" show-overflow-tooltip>
          </el-table-column>


        </el-table>
      </div>


    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-divider content-position="left">
        <div style="display: flex; text-align: center;align-items: center">
            <span style="color: #409EFF;">
              结算行
            </span>
        </div>
      </el-divider>
      <el-button type="primary" plain @click="update" v-if="updateIfButton">修改</el-button>
      <el-table :data="tableDataLine" border highlight-current-row height="300">
        <!--          <el-table-column type="selection" fixed></el-table-column>-->
        <el-table-column v-if="true" prop="itemNm" label="物料名称" width="140" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="transTasteSci" label="品位" header-align="center" align="center" width="140"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="transWaterSci" label="水分" header-align="center" align="center" width="140"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + (currentPageOutRecord - 1) * pageSizeOutRecord + 1 }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="true" prop="stoOutNo" label="出库单号" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column> -->

        <el-table-column v-if="true" prop="itemCd" label="物料编码" width="130" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>


        <!-- <el-table-column v-if="true" prop="stoOutWgt" label="湿基量" header-align="center" align="center" width="140"
                         show-overflow-tooltip>
        </el-table-column> -->

        <!-- <el-table-column v-if="true" prop="invLine" label="结算行号" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column> -->
        <el-table-column v-if="true" prop="uom" label="计量单位" header-align="center" align="center" width="140"
                         :formatter="formatter"
                         show-overflow-tooltip>
        </el-table-column>
        <!-- <el-table-column v-if="false" prop="itemType" label="物料类型" header-align="center" align="center"
                         width="140"
                         show-overflow-tooltip>
        </el-table-column> -->
        <el-table-column v-if="true" prop="contrNo" label="合同编号" header-align="center" align="center"
                         width="140"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="khContrNo" label="对方合同编号" header-align="center" align="center"
                         width="140"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="invNo" label="结算单号" header-align="center" align="center" width="140"
                         show-overflow-tooltip>
        </el-table-column>

        <!-- <el-table-column v-if="true" prop="tmsNo" label="物流计量业务单号" header-align="center" align="center"
                         width="140"
                         show-overflow-tooltip>
        </el-table-column> -->
        <!-- <el-table-column v-if="true" prop="syiNo" label="检化验业务单号" header-align="center" align="center"
                         width="140"
                         show-overflow-tooltip>
        </el-table-column> -->
        <el-table-column v-if="true" prop="remark" label="备注" header-align="center" align="center" width="140"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="qty" label="数量" header-align="center" align="center" width="120"  fixed="left"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="qtyUpdate" label="修改数量" header-align="center" align="center" width="160"  fixed="left"
                         show-overflow-tooltip>
          <template #header>
            <span style="color: red">修改数量</span>
          </template>
          <template #default="scope">
            <el-input-number v-if="!scope.row.qtyEdit" :min="0" style="width: 100%"
                             @change="outquantityChangeInvPrice( scope.row ,'A' , scope.$index)"
                             v-model="scope.row.qtyUpdate"></el-input-number>

          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="invPrice" label="结算单价" header-align="center" align="center"
                         fixed="left"
                         width="140"
                         show-overflow-tooltip>
          <!--            <template #default="scope">-->
          <!--              <el-input-number v-if="!scope.row.qtyEdit" :min="0"-->
          <!--                               @change="outquantityChangeInvPrice( scope.row ,scope.$index)"-->
          <!--                               v-model="scope.row.invPrice"></el-input-number>-->
          <!--            </template>-->
        </el-table-column>

        <el-table-column v-if="true" prop="invPriceUpdate" label="修改单价" header-align="center" align="center"
                         fixed="left"
                         width="160"
                         show-overflow-tooltip>
          <template #header>
            <span style="color: red">修改单价</span>
          </template>
          <template #default="scope">
            <el-input-number v-if="!scope.row.qtyEdit" :min="0" style="width: 100%"
                             @change="outquantityChangeInvPrice( scope.row ,'B' ,scope.$index)"
                             v-model="scope.row.invPriceUpdate"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="invAmt" label="结算金额" header-align="center" align="center" width="140"
                         fixed="left"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="invAmtUpdate" label="新结算金额" header-align="center" align="center" width="140"
                         fixed="left"
                         show-overflow-tooltip>
          <template #header>
            <span style="color: red">新结算金额</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" header-align="center" align="center" width="120px" fixed="right">
          <template #default="scope">
            <el-button plain type="warning" @click="searchReport(scope.row)" >打印</el-button>
          </template>
        </el-table-column> -->

      </el-table>

    </el-card>

    <el-dialog :close-on-click-modal="false" draggable v-model="reportDialogVisible" width="900px" top="5vh">
      <fine-report ref="finereport" :reportPath="reportPath"></fine-report>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  nextTick
} from 'vue'

const {
  proxy
} = getCurrentInstance()
import style from '@/tools/style'
import SelectorComponent from "@/views/sal/components/Selector_component.vue";

const cardBodyStyle = ref(style.card)
/**
 * 新增表单form
 */
const form = ref({
  id: '',

})
const tableDataMx = ref([])

import {
  useWorkflowStore
} from "@/stores/workflow"

const workflow = useWorkflowStore()
const dictList = ref({})
const dictData = () => {
  var url = 'framework/Common/querySelectorList'
  var param = {
    type: JSON.stringify(['MEASURING_UNIT', 'COM_PAY_MTH', 'INV_FLAG', 'PRICE_DCN_MTH'])
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      dictList.value = response.data.data
      console.log(dictList.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })

}
const currentPage = ref(1)
const pageSize = ref(10)
const querySettlement = ref({
  contrNo: '',
  contrLineNo: ''
})
const getFrom = () => {
  var url = 'sal/InvHead/queryByWorkId'
  var param = {
    workId: workflow.workId
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      form.value = response.data.data
      form.value.invFlag = String(form.value.invFlag)
      console.log(form.value)
      getTableDataLine(response.data.data.invNo)
      querySettlement.value = {
        contrNo: response.data.data.contrNo,
        contrLineNo: response.data.data.taxRateLine,
      }
    console.log(querySettlement.value)
      getTableDataSettlement()
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const currentPageOutRecord = ref(1)
const pageSizeOutRecord = ref(5)
const tableDataLine = ref([])
const tableDataSettlement = ref([])
const getTableDataLine = (id) => {
  var url = 'sal/InvLine/queryNoPerssion'
  var param = {
    page: 1,
    rows: 9999,
    params: JSON.stringify({fId: id})
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data.data.records)
      tableDataLine.value = response.data.data.records
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const getTableDataSettlement = () => {
  var url = 'cot/Settlement/queryByContrNoAndConLineNo'
  var param = {
    params: JSON.stringify(querySettlement.value)
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      tableDataSettlement.value = response.data.data
      // totalRowsSettlement.value = response.data.data.total
      console.log(tableDataSettlement.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const formatter = (row, column, cellValue, index) => {
  if (!cellValue || cellValue == null || cellValue == '') {
    return cellValue
  }
  switch (column.property) {
    case 'payMth':
      cellValue = dictList.value && Array.isArray(dictList.value.COM_PAY_MTH)
          ? dictList.value.COM_PAY_MTH.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
    case 'invFlag':
      cellValue = dictList.value && Array.isArray(dictList.value.INV_FLAG)
          ? dictList.value.INV_FLAG.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
    case 'uom':
      cellValue = dictList.value && Array.isArray(dictList.value.MEASURING_UNIT)
          ? dictList.value.MEASURING_UNIT.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break;
  }
  return cellValue

}
const outquantityChangeInvPrice = (row, val , index) =>{
  var json = {
    id: row.id,
    update: val,
    qtyUpdate: row.qtyUpdate,
    invPriceUpdate: row.invPriceUpdate,
  }

  if (row.qtyUpdate != 0 && row.invPriceUpdate == 0){
    var amt = row.qtyUpdate * row.invPrice
    tableDataLine.value[index].invAmtUpdate = Math.round(amt * 100)/100
    json.invAmtUpdate = Math.round(amt * 100)/100
  } else if (row.qtyUpdate == 0 && row.invPriceUpdate != 0){
    var amt = row.qty * row.invPriceUpdate
    tableDataLine.value[index].invAmtUpdate = Math.round(amt * 100)/100
    json.invAmtUpdate = Math.round(amt * 100)/100
  } else if (row.qtyUpdate != 0 && row.invPriceUpdate != 0){
    console.log(row)
    if(row.qty == row.qtyUpdate && row.invPriceUpdate == row.invPrice) {
      row.invAmtUpdate = row.invAmt
      json.invAmtUpdate = row.invAmt
    } else {
      var amt = row.qtyUpdate * row.invPriceUpdate
      tableDataLine.value[index].invAmtUpdate = Math.round(amt * 100)/100
      json.invAmtUpdate = Math.round(amt * 100)/100
    }
  }

  var url = 'sal/InvLine/saveUpdate'
  var param = {
    json: JSON.stringify(json)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      ElMessage({
        type: 'success',
        message: '修改成功!'
      })
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const update = () =>{

  tableDataLine.value.forEach(item => item.qtyEdit = false)

}

const updateIf = () =>{
  var post = JSON.parse(localStorage.getItem("post"));
  for( var i = 0; i < post.length ; i++){
    if (post[i].postCode == 'P01007' || post[i].postName == '销售科室负责人'){
      updateIfButton.value = true
      return
    }
  }
}
const updateIfButton = ref(false)
import FineReport from '@/components/report/FineReport.vue'
const reportPath = ref('')
const finereport = ref(null)
const reportDialogVisible = ref(false);

const searchReport = (row) => {
  var url = 'sci/JkJlxx/queryHyjg'
  var param = {
    zph: row.transIdSci
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      var jsgs = row.invPriceBase
      var endPrice = Number(row.invPriceBase)
      var jhyjsgs =""
      var ar = 0
      for (var i = 0; i < tableDataSettlement.value.length; i++) {
        for (var j = 0; j < response.data.data.length; j++) {
          if (tableDataSettlement.value[i].settleItem == response.data.data[j].xiangmuMc) {
            if (Number(response.data.data[j].xiangmuXyz) <= Number(tableDataSettlement.value[i].settleValueTo ) && Number(response.data.data[j].xiangmuXyz) >=  Number(tableDataSettlement.value[i].settleValueFrom)){
              var pr = (Number(response.data.data[j].xiangmuXyz) - Number(tableDataSettlement.value[i].referenceValue)) / Number(tableDataSettlement.value[i].settleSpan) * Number(tableDataSettlement.value[i].settleDiffer)
              endPrice += Math.round(pr * 100)/100
              if (ar == 0){
                jhyjsgs = jhyjsgs +" ( " + Number(response.data.data[j].xiangmuXyz) + " - " + Number(tableDataSettlement.value[i].referenceValue) + " ) "
                    + " / " + Number(tableDataSettlement.value[i].settleSpan) + " * " + Number(tableDataSettlement.value[i].settleDiffer)

              } else {
                jhyjsgs = jhyjsgs +" + ( " + Number(response.data.data[j].xiangmuXyz) + " - " + Number(tableDataSettlement.value[i].referenceValue) + " ) "
                    + " / " + Number(tableDataSettlement.value[i].settleSpan) + " * " + Number(tableDataSettlement.value[i].settleDiffer)

              }
              ar += 1
            }
          }
        }
      }
      jsgs =  " ( " + jhyjsgs + " ) +"  + endPrice
      console.log(jsgs)
      reportPath.value = 'jlyypt/salResultSP.cpt&id='+ row.id + "&contrId=" + form.value.contrId + "&conLineId=" + form.value.taxRateLine + "&jsgs=" + jsgs
      reportDialogVisible.value = true
      finereport.value.refresh()
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })


}

onMounted(() => {
  dictData()
  getFrom()
  updateIf()


})
</script>

<style scoped>
::v-deep .el-form-item {
  width: 100%
}

::v-deep .el-dialog__body {
  background-color: #F2F6FC;
}

.el-date-editor--date {
  width: 100%;
}

::v-deep .diaClass .el-form-item__label {
  width: 140px !important;
}

</style>
