<template>
  <div>

    <el-card :body-style="cardBodyStyle">
      <el-form :model="query" label-width="auto" label-position="right">
        <el-row :gutter="10" style="">
          <el-col :span="5">
            <el-form-item label="结算日期" style="margin-bottom: 5px;">
              <el-date-picker
                  style="width: 100%"
                  v-model="query.invDtList"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="结算单号" style="margin-bottom: 5px;">
              <el-input v-model="query.invNo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="客户名称" style="margin-bottom: 5px;">
              <el-input v-model="query.tradePartnerName" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="合同号" style="margin-bottom: 5px;">
              <el-input v-model="query.contrNo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-button type="primary" link @click="reset">重置</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" link @click="queryShow = !queryShow">
              高级查询
              <el-icon v-if="queryShow">
                <ArrowUp/>
              </el-icon>
              <el-icon v-else>
                <ArrowDown/>
              </el-icon>
            </el-button>
          </el-col>
          <el-col :span="5" v-if="queryShow">
            <el-form-item label="结算单类型" style="margin-top: 5px;margin-bottom: 5px;">
              <el-select v-model="query.payMth" clearable>
                <el-option
                    v-for="item in dicList.COM_PAY_MTH"
                    :key="item.dicCode"
                    :label="item.dicName"
                    :value="item.dicCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5" v-if="queryShow">
            <el-form-item label="是否被驳回" style="margin-top: 5px;margin-bottom: 5px;">
              <el-input v-model="queryUserDesc" placeholder="" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <ButtonBar @search="handleSearch" @add="handleAdd" @download="searchReport"></ButtonBar>

    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row :height=height
                @selection-change="handleSelectionChange" @row-click="cellHover">
        <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="invNo" label="结算单号" width="200" header-align="center"
                         align="center" show-overflow-tooltip>
          <!-- <template #default="scope">
            <el-button @click="handleInfo(scope.row)" type="primary" link>{{ scope.row.invNo }}</el-button>
          </template> -->
        </el-table-column>
        <el-table-column v-if="true" prop="invDt" label="结算日期" width="130" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="invTy" label="开票类型" width="140" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="payMth" label="结算类型" header-align="center" align="center" width="140"
                         :formatter="formatter"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="contrNo" label="合同编号" header-align="center" align="center"
                         width="150"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="khContrNo" label="对方合同编号" header-align="center" align="center"
                         width="110"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="workModel.flowStatusName" label="流程状态" width="120"
                         header-align="center" align="center"
                         show-overflow-tooltip>
          <template #default="{ row }">
            <div>
              <el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">
                {{ row.workModel.flowStatusName }}
              </el-tag>
              <el-tag type="success" v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">
                {{ row.workModel.flowStatusName }}
              </el-tag>
              <el-tag type="danger"
                      v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">
                {{ row.workModel.flowStatusName }}
              </el-tag>
              <el-tag type="warning" v-else>'---'</el-tag>
            </div>

          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="workModel.flowNode" label="当前节点" width="120" header-align="center"
                         align="center"
                         show-overflow-tooltip>
          <template #default="{ row }">
            <div>
              <el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">
                {{ row.workModel.flowNode }}
              </el-tag>
              <el-tag type="success" v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">
                {{ row.workModel.flowNode }}
              </el-tag>
              <el-tag type="danger"
                      v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">
                {{ row.workModel.flowNode }}
              </el-tag>
              <el-tag type="warning" v-else>'---'</el-tag>
            </div>

          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="tradePartnerCode" label="客户编号" header-align="center" align="center"
                         width="140"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="tradePartnerName" label="客户名称" header-align="center" align="center"
                         width="140"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="false" prop="taxRate" 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="140"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="invAmt" label="结算金额" header-align="center" align="center" width="140"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="invDesc" label="开票说明" header-align="center" align="center"
                         width="140"
                         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="invFlag" label="结算标识" header-align="center" align="center"
                         :formatter="formatter"
                         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" label="操作" header-align="center" align="center" width="300" fixed="right"
                         show-overflow-tooltip>
          <template #default="scope">
            <!--                <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>-->
            <!--                <el-button plain type="danger" @click="handleDelete(scope.row )">删除</el-button>-->

            <!-- <el-button plain type="warning" @click="handleEdit(scope.row)"
                       v-show="scope.row.workId === '' || scope.row.workModel.opType === '1'">编辑
            </el-button> -->
            
            <el-button plain type="success" @click="handleSubmit(scope.row ) "
                       v-show="scope.row.workId === '' || scope.row.workModel.opType === '1'">发起
            </el-button>
            <el-button plain type="primary" @click="handleDetail(scope.row )" v-show="scope.row.workId !== ''">
              详情
            </el-button>
            <el-button plain type="danger" @click="handleDelete(scope.row )"
                       v-show="scope.row.workId === '' || scope.row.workModel.opType === '1'">删除
            </el-button>
            <el-button plain type="info" @click="handleCancel(scope.row )"
                       v-show="scope.row.workId !== '' && scope.row.workModel.opType !== '1' && scope.row.workModel.flowStatus !== '170'">
              撤回
            </el-button>

          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                     background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <el-dialog class="diaClass" :close-on-click-modal="false" draggable title="新增" v-model="dialogVisible" fullscreen
               top="5vh" @open="openDialog" @close="diaClose">
      <el-card :body-style="cardBodyStyle">
        <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
          <el-divider content-position="left">
            <div style="color: #409EFF">结算信息</div>
          </el-divider>
          <div style="display: flex;">
            <el-card style="width: 100%;margin-right: 1px">
              <el-row>
                <el-col :span="12">
                  <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="12">
                  <el-form-item label="结算日期" prop="invDt" style="width: 100%">
                    <el-date-picker
                        style="width: 100%"
                        v-model="form.invDt"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="申请日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="打包单" prop="headNo" style="width: 100%">
                    <el-select v-model="form.headNo" placeholder="请选择" clearable style="">
                      <el-option v-for="item in packageList" :key="item.headNo" :label="item.headNo"
                                 @click.native="headNoClick(item)"
                                 :value="item.headNo"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="合同编号" prop="contrNo" style="width: 100%">
                    <el-input v-model="form.contrNo" readonly>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="对方合同编号" prop="khContrNo">
                    <el-input v-model="form.khContrNo" readonly>

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

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

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

                <el-col :span="12">
                  <el-form-item label="结算类型" prop="payMth">
                    <SelectorComponent :optionList="dicList.COM_PAY_MTH" :value="form.payMth"
                                       @change="payMathSelect"/>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="结算物料" prop="itemNm">
                    <el-input v-model="form.itemNm" readonly>

                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="物料编码" prop="itemCd">
                    <el-input v-model="form.itemCd" readonly>

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

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

                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="开始时间" prop="qty">
                    <el-input v-model="form.startDate" readonly>

                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间" prop="invAmt">
                    <el-input v-model="form.endDate" readonly>

                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结算标识" prop="invFlag">
                    <SelectorComponent :optionList="dicList.INV_FLAG" :value="form.invFlag" :allowSelect="true"
                                       @change="invFlagSelect"/>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="开票说明">
                    <el-input
                        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
                        v-model="form.remark"
                        :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea"
                        placeholder=""
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <el-card style="width: 100%;margin-right: 1px">
              <el-row>
                <el-table :data="salTransSciWeightedList" border highlight-current-row height="400">
                  <el-table-column type="index" label="序号" align="center" width="60">
                    <template #default="scope">
                      <span>{{ scope.$index + (currentPageLine - 1) * pageSizeLine + 1 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="true" prop="sciNo" label="加权平均编号" width="150" header-align="center"
                                   align="center" show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column v-if="true" prop="sciDt" label="业务日期时间" width="130" header-align="center"
                                   align="center" show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column v-if="true" prop="sciProjectName" label="检化验项目名称" header-align="center"
                                   align="center"
                                   width="150"
                                   show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column v-if="true" prop="sciProjectNum" label="检化验项目结果" header-align="center"
                                   align="center"

                                   show-overflow-tooltip>
                  </el-table-column>

                </el-table>

              </el-row>
            </el-card>
          </div>

        </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-affix position="bottom" :offset="20">
          <el-card>
            <el-button type="primary" plain @click="getNewPrice">结算</el-button>
            <el-button type="primary" plain @click="getNewPriceLG">莱钢月末结算</el-button>
            <el-button type="primary" plain @click="getNewPriceCu">铜结算</el-button>
            <h3>
              <span>当前物料基价= {{ form.priceBase }}</span>
            </h3>
            <h3 style="display: flex;">
              <span style="width: 100px">结算单价=</span>
              <span v-if="!LGInput">{{ form.invPrice }}</span>
              <el-input v-if="LGInput" v-model="form.invPrice"></el-input>
            </h3>
            <h3 style="display: flex">
              <span style="width: 100px">结算金额=</span>
              <span v-if="!LGInput">{{ form.invAmt }}</span>
              <el-input v-if="LGInput" v-model="form.invAmt"></el-input>
            </h3>
            <h3 style="display: flex;" v-if="LGInput">
              <span style="width: 100px">补差总额=</span>
              <el-input v-model="form.invMakeUp"></el-input>
            </h3>
          </el-card>
        </el-affix>
      </el-card>


      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSave(ruleFormRef)" plain>保存</el-button>
          <el-button type="danger" @click="handleCancelSave" plain>取消</el-button>
        </div>
      </template>
    </el-dialog>

    <PopupCot ref="PopupRefHT" :params="contrTyStr" @receive-from-child="retu"></PopupCot>

    <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
} from 'vue'
import {Search} from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const {
  proxy
} = getCurrentInstance()


import style from '@/tools/style'

const cardBodyStyle = ref(style.card)

const tableStatus = reactive({
  tableRowEditIndex: undefined,
  tableColumnEditIndex: undefined,
})
import SearchBar from '@/components/SearchBar.vue';
import PopupMenuTree from '@/components/PopupMenuTree.vue'
import ButtonBar from "@/components/ButtonBar.vue";
import Selector_component from "@/views/sal/components/Selector_component.vue";
import PopupCot from "@/views/cot/components/PopupCot.vue";
import SelectorComponent from "@/views/sal/components/Selector_component.vue";
import tools from "@/tools";
import {workflowCancel, workflowSubmit} from "@/tools/workflow.js";

const searchBarRef = ref(null)
const formItem = ref([
  {
    prop: 'birthDate',
    type: 'input',
    label: '订单号'
  },
  {
    prop: 'age',
    type: 'input',
    label: '客户名称',
    searchButton: true,
    searchCallback: 'showPop'
  }

])

const tableTwoUpShow = ref(false)
const dialogVisible = ref(false)
const dialogVisibleEdit = ref(false)
const dialogVisibleInfo = ref(false)


/**
 *   查询
 */

const query = ref({
  invDtList: ['', ''],
  invNo: '',
  tradePartnerName: '',
  contrNo: '',
})
// 首 列表
const tableData = ref([])

const tableDataLine = ref([])
const tableDataOutRecord = ref([])


const getTableData = () => {
  var url = 'sal/InvHead/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 *   查询
 */
/**
 * 分页
 */
const currentPage = ref(1)
const currentPageOutRecord = ref(1)
const currentPageLine = ref(1)
const totalRows = ref(0)
const totalRowsOutRecord = ref(0)
const totalRowsLine = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSizesOutRecord = ref([5, 10, 20, 30, 40])
const pageSizesLine = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const pageSizeOutRecord = ref(5)
const pageSizeLine = ref(5)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

const PopupMenuTreeRef = ref(null)
const showPop = () => {
  console.log('showPop')
  PopupMenuTreeRef.value.show()
}
/**
 * 新增表单form
 */
const form = ref({
  id: '',
  contrNo: '',
  khContrNo: '',
  tradePartnerId: '',
  tradePartnerName: '',
  tradePartnerCOde: '',
  invFlag: '1',
  invStartTime: '',
  invEndTime: proxy.$dayjs(),

})


// 校验
const rules = reactive({
  contrNo: [
    {required: true, message: '不允许为空', trigger: 'blur' | 'change'},
  ],
  payMth: [
    {required: true, message: '不允许为空', trigger: 'blur' | 'change'},
  ],
  headNo: [
    {required: true, message: '不允许为空', trigger: 'blur' | 'change'},
  ],


})

// 首-列表 编辑
const handleEdit = (row) => {
  dialogVisible.value = true
  console.log(row)
  form.value = {}
  form.value = row
  form.value.invFlag = String(form.value.invFlag)
  form.value.edit = true
  tableDataOutRecord.value = []
  tableDataSettlement.value = []

  conLine(row.contrNo)


  querySettlement.value = {
    contrId: row.contrId,
    conLineId: row.taxRateLine,
  }

  getTableDataSettlement(querySettlement.value)


  

  multipleSelection.value = []


  setTimeout(() => {
    // jisuan()
  }, 1000);
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var url = 'sal/InvHead/invRemove'
        var param = {
          id: row.id
        }
        proxy.$axios.get(url, param).then(response => {
          if (response.data.code == '0') {
            console.log(response.data.data)
            ElMessage({
              type: 'success',
              message: '删除成功！',
            });
            getTableData()
          } else {
            ElMessage.error('操作失败！' + response.data.msg)
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

const packageList = ref([])
const handleAdd = () => {
  LGInput.value = false
  form.value = {
    invDt: proxy.$dayjs().format('YYYY-MM-DD'),
    invFlag: "1",
  }
  dialogVisible.value = true
  tableDataOutRecord.value = []
  tableDataSettlement.value = []
  tableDataLine.value = []

  getPackageList()

}
const getPackageList = () => {
  var url = 'sal/TostoHeader/queryAll'
  var param = {
    params: JSON.stringify({})
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      packageList.value = response.data.data.records

    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const dicList = ref([])
//获取字典集合
const getDicList = () => {
  tools.dic.getDicList(['MEASURING_UNIT', 'COM_PAY_MTH', 'INV_FLAG', 'PRICE_DCN_MTH']).then((response => {

    dicList.value = response.data.data
  }))
}

const handleCancelSave = () => {
  dialogVisible.value = false
}

const PopupRefHT = ref(null)

const retu = (val) => {
  form.value.taxRate = ''
  tableDataOutRecord.value = []
  console.log("vla", val)
  form.value.contrNo = val.contrNo
  form.value.khContrNo = val.khContrNo
  form.value.tradePartnerId = val.supplierId
  form.value.tradePartnerCode = val.supplierCd
  form.value.tradePartnerName = val.supplierNm

  form.value.taxRateLine = ''

  form.value.priceDcnMth = val.priceDcnMth
  form.value.contrId = val.id

  conLine(val.contrNo)
}

const contrTyStr = ref({
  contrTy: '10',
  supplierCd: ''
})

const lineList = ref([])
const lineKey = ref()
const conLine = (val) => {
  lineList.value = []
  var url = 'cot/Line/query'
  var param = {
    page: 1,
    rows: 999999,
    params: JSON.stringify({contrNo: val})
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      lineKey.value = new Date().getTime()
      console.log(response.data.data.records)
      // var arr = []
      // for(var i = 0 ; i < response.data.data.records.length ; i++){
      // arr.push(response.data.data.records[i].taxRate)
      // }
      // let uniqueArr = [...new Set(arr)];

      lineList.value = response.data.data.records
      if (form.value.taxRateLine != null && form.value.taxRateLine != '') {
        for (var i = 0; i < lineList.value.length; i++) {
          if (lineList.value[i].id == form.value.taxRateLine) {
            form.value.taxPriceBill = lineList.value[i].taxPriceBill
            form.value.taxPriceCash = lineList.value[i].taxPriceCash
            break;
          }
        }
      }


    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })

}
const queryShow = ref(false)
const show = () => {
  queryShow.value = true
}

const taxRateChange = (val) => {
  form.value.taxRate = val.taxRate
  tableDataOutRecord.value = []
  querySettlement.value = {
    contrId: form.value.contrId,
    conLineId: val.id,
  }
  getTableDataSettlement()
  form.value.taxPriceBill = val.taxPriceBill
  form.value.taxPriceCash = val.taxPriceCash
  // if (Number(val.taxPriceBill) != 0) {
  //   form.value.price = val.taxPriceBill
  // } else {
  //   form.value.price = val.taxPriceCash
  // }
  form.value.taxRateLine = val.id
  // console.log(val)
  form.value.transTasteSci = val.specType
  // if (form.value.priceDcnMth != '10'){
  // 取最新定价，
  // getNewPrice(val.itemCd)
  // }
}


const payMathSelect = (val) => {
  form.value.payMth = val
  console.log(val)
  tableDataOutRecord.value = []
  // queryOutRecord()
}
const invFlagSelect = (val) => {
  form.value.invFlag = val
  console.log(val)
}

const ruleFormRef = ref(null)
const handleSave = (ruleFormRef) => {
  form.value.invStartTime = form.value.startDate
  form.value.invEndTime = form.value.endDate
  if (!ruleFormRef) return
  ruleFormRef.validate((valid) => {
    if (valid) {
      // form.value.invLineList = multipleSelection.value
      var url = 'sal/InvHead/invSave'
      var param = {
        json: JSON.stringify(form.value),
        lines: JSON.stringify(multipleSelection.value),
        headerData: JSON.stringify(headerData.value)
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()
          dialogVisible.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            type: 'error',
            message: '操作失败' + response.data.msg
          })
        }
      });
    } else {
      console.log('error submit!')
      return false
    }

  })
}
const handleSaveEdit = (ruleFormRef) => {
  if (!ruleFormRef) return
  ruleFormRef.validate((valid) => {
    if (valid) {
      // form.value.invLineList = multipleSelection.value
      multipleSelection.value
      for (var i = 0; i < tableDataLine.value.length; i++) {
        multipleSelection.value.push(tableDataLine.value[i])
      }

      var url = 'sal/InvHead/save'
      var param = {
        json: JSON.stringify(form.value),
        lines: JSON.stringify(multipleSelection.value),
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()
          dialogVisibleEdit.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            type: 'error',
            message: '操作失败' + response.data.msg
          })
        }
      });
    } else {
      console.log('error submit!')
      return false
    }

  })
}

const handleInfo = (row) => {
  var url = 'sal/InvHead/queryByPK'
  var param = {
    id: row.id,
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      form.value = {}
      form.value = response.data.data
      form.value.invFlag = String(response.data.data.invFlag)
      querySettlement.value = {
        contrId: response.data.data.contrId,
        conLineId: response.data.data.taxRateLine,
      }

      getTableDataSettlement()
      dialogVisibleInfo.value = true
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const closeDialog = (row) => {

  form.value = {}

}

const formatter = (row, column, cellValue, index) => {
  if (!cellValue || cellValue == null || cellValue == '') {
    return cellValue
  }
  switch (column.property) {
    case 'payMth':
      cellValue = dicList.value && Array.isArray(dicList.value.COM_PAY_MTH)
          ? dicList.value.COM_PAY_MTH.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
    case 'invFlag':
      cellValue = dicList.value && Array.isArray(dicList.value.INV_FLAG)
          ? dicList.value.INV_FLAG.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
    case 'uom':
      cellValue = dicList.value && Array.isArray(dicList.value.MEASURING_UNIT)
          ? dicList.value.MEASURING_UNIT.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break;
  }
  return cellValue

}

const reset = () => {
  query.value = {
    invDtList: ['', ''],
    invNo: '',
    tradePartnerName: '',
    contrNo: '',
  }
}

const submit = () => {
  ElMessage({
    type: 'info',
    message: '暂不支持提交！'
  })
}
const cellId = ref('')
const cellHover = (row) => {
  if (cellId.value != row.id) {
    tableDataLine.value = []
    cellId.value = row.id
  }


}

const multipleSelection = ref([])

const multipleSelectionSettlement = ref([])
const handleSelectionChangeSettlement = (val) => {
  multipleSelectionSettlement.value = val
}
const querySettlement = ref({
  contrId: '',
  conLineId: ''
})
const tableDataJianHuaYan = ref([])
const tableDataSettlement = ref([])
const getTableDataSettlement = (val) => {
  var url = 'cot/Settlement/queryByContrNoAndConLineNo'
  var param = {
    params: JSON.stringify(val)
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      tableDataSettlement.value = response.data.data
      // totalRowsSettlement.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const diaClose = () => {
  form.value = {}
  tableDataOutRecord.value = []
  tableDataSettlement.value = []
  lineList.value = []
}

const flowId = ref('SalResultFinance')
const handleSubmit = (row) => {
  ElMessageBox.confirm(
      '确定提交流程?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  ).then(() => {
    var obj = {
      id: row.id
    }
    return workflowSubmit(
        flowId.value,
        '销售结算审批流程',
        '初始化提交',
        JSON.stringify(obj),
        row.workId,
        row.trackId)
  }).then((result) => {
    if (result.status === 'success') {

      console.log(result)
      // 将结果返回的workId和trackId保存
      var url = 'sal/InvHead/submitFq'
      var process = {
        'id': row.id,
        'workId': result.workId,
        'trackId': result.trackId,
      }
      var param = {
        json: JSON.stringify(process),
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code === 0) {
          // form.value = response.data.data
          ElMessage({
            type: 'success',
            message: '提交审批成功',
          })
          getTableData()
        }
      })
    } else {
      ElMessage({
        type: 'error',
        message: '提交审批失败' + response.data.msg
      });
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消提交',
    })
  })
}

const handleDetail = (row) => {
  if (row.workId === null) {
    ElMessage({
      type: 'info',
      message: '无法查看',
    })
  } else {

    sessionStorage.setItem('workflowQuery', JSON.stringify({
      flowId: flowId.value,
      workId: row.workId,
      trackId: row.trackId,
      date: new Date().getTime()
    }))

    proxy.$router.push({
      path: '/workflow/detail',
    })

  }
}

const handleCancel = (row) => {
  ElMessageBox.confirm(
      '确定撤回审批?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  ).then(() => {
    return workflowCancel(row.workId, row.trackId);
  }).then((result) => {
    if (result.status === 'success') {
      ElMessage({
        type: 'success',
        message: '撤回审批成功',
      })
      getTableData()
    } else {
      ElMessage({
        type: 'error',
        message: '撤回审批失败，' + result.msg
      });
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消提交',
    })
  })
}
const pDate = ref('')
const pReportDate = ref('')
import FineReport from '@/components/report/FineReport.vue'
import { computed } from 'vue'
import { ElMessage } from 'element-plus'

const reportPath = ref('')
const finereport = ref(null)
const reportDialogVisible = ref(false);
const searchReport = () => {
  var date = proxy.$dayjs().format('YYYY年MM月DD日')
  console.log(date)
  if (checkRow.value.length == 1) {
    if (checkRow.value[0].processInstanceStatus == '170') {
      var list = []
      var url = 'workflow/process/history'
      var param = {
        workId: checkRow.value[0].workId
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == '0') {
          list = response.data.data.records
          var kezhang = ""
          var lingdao = ""
          console.log("list ", list)
          for (let i = list.length - 1; i >= 0; i--) {
            if (list[i].nodeid === 'Node2') {
              kezhang = list[i].username;
              break;
            }
          }
          for (let i = list.length - 1; i >= 0; i--) {
            if (list[i].nodeid === 'Node3') {
              lingdao = list[i].username;
              break;
            }
          }
          console.log("kezhang ", kezhang)
          console.log("lingdao ", lingdao)
          reportPath.value = 'jlyypt/salResult.cpt&para1=' + date + '&para2=' + String(localStorage.getItem('userDesc')) + "&id=" + checkRow.value[0].id + "&kezhang=" + kezhang + "&lingdao=" + lingdao
          reportDialogVisible.value = true
          finereport.value.refresh()
        } else {
          ElMessage.error('操作失败！' + response.data.msg)
        }
      })
    } else {
      reportPath.value = 'jlyypt/salResult.cpt&para1=' + date + '&para2=' + String(localStorage.getItem('userDesc')) + "&id=" + checkRow.value[0].id
      reportDialogVisible.value = true
      finereport.value.refresh()
    }

    // pDate.value = monthQuery.value.monthValue.getFullYear() + String(monthQuery.value.monthValue.getMonth() + 1).padStart(2, '0')
    // pReportDate.value = formatDateToYYYYMMDD(new Date())

  } else {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据！',
    })
  }

}
// 选中行
const checkRow = ref([])
const handleSelectionChange = (val) => {
  checkRow.value = val
}

const salTransSciWeightedList = ref([])

const headNoClick = (val) => {
  console.log(val)
  form.value.contrNo = val.contrNo
  form.value.khContrNo = val.khContrNo
  form.value.tradePartnerName = val.tradePartnerName
  form.value.priceDcnMth = val.priceDcnMth
  form.value.tradePartnerCode = val.tradePartnerCode
  form.value.itemCd = val.itemCd
  form.value.itemNm = val.itemNm
  form.value.startDate = val.startDate
  form.value.endDate = val.endDate
  form.value.specType = val.specType

  form.value.tostoHeaderNo = val.headNo

  var headId = {
    headId: val.id
  }
  getSalTransSciWeighted(headId)

  // 结算标准
  var map = {
    contrNo: val.contrNo,
    contrLineNo: val.contrLineNo,
  }

  getTableDataSettlement(map)
}

const getSalTransSciWeighted = (val) => {
  // 获取 打包相关联的 检化验加权数据
  var url = 'sal/SalTransSciWeighted/queryAll'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(val)
  }

  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      salTransSciWeightedList.value = response.data.data.records
      if (response.data.data.records.length > 0) {
        form.value.qty = response.data.data.records[0].qty
      }
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

// 获取最新定价
const getNewPrice = () => {
  form.value.priceBase = ''
  form.value.invPrice = ''
  form.value.invAmt = ''
  if (form.value.payMth && form.value.itemCd) {
    LGInput.value = false
    var url = 'sal/UpriceLine/selectPriceByItemCdAndDateFw'
    var param = {
      itemCd: form.value.itemCd,
      specType: form.value.specType,
      startDate: form.value.startDate,
      endDate: form.value.endDate,
    }
    if (form.value.itemNm == '铜精矿' || form.value.itemNm == '铜精矿2') {
      ElMessage({
        type: 'warning',
        message: '铜精矿暂不支持结算！',
      })
    } else {
      proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
          if (form.value.payMth == 'A') {
            form.value.priceBase = response.data.data.priceCash
          } else {
            form.value.priceBase = response.data.data.priceBill
          }
          form.value.upriceLineId = response.data.data.id
          var endPrice = form.value.priceBase
          for (var i = 0; i < tableDataSettlement.value.length; i++) {
            for (var j = 0; j < salTransSciWeightedList.value.length; j++) {
              if (tableDataSettlement.value[i].settleItem == salTransSciWeightedList.value[j].sciProjectName)
                if (Number(salTransSciWeightedList.value[j].sciProjectNum) <= Number(tableDataSettlement.value[i].settleValueTo)
                    && Number(salTransSciWeightedList.value[j].sciProjectNum) >= Number(tableDataSettlement.value[i].settleValueFrom)) {
                  var pr = (Number(salTransSciWeightedList.value[j].sciProjectNum) - Number(tableDataSettlement.value[i].referenceValue)) / Number(tableDataSettlement.value[i].settleSpan) * Number(tableDataSettlement.value[i].settleDiffer)
                  endPrice += Math.round(pr * 100) / 100
                }
            }
          }
          form.value.invPrice = endPrice
          var amt = endPrice * form.value.qty
          form.value.invAmt = Math.round(amt * 100) / 100


        }
      })
    }

  } else {
    ElMessage({
      type: 'warning',
      message: '请先选择结算信息！',
    })
  }


}
const getNewPriceLG = () => {
  form.value.priceBase = ''
  form.value.invPrice = ''
  form.value.invAmt = ''
  console.log(form.value)
  if(form.value.tradePartnerCode != 'D01000011' && form.value.tradePartnerCode != 'D01000012') {
    ElMessage.warning('该公司不属于莱钢结算')
    return
  }
  if (form.value.payMth && form.value.itemCd) {
    var url = 'sal/UpriceLine/selectPriceByItemCdAndDateFw'
    var param = {
      itemCd: form.value.itemCd,
      specType: form.value.specType,
      startDate: form.value.startDate,
      endDate: form.value.endDate,
    }
    LGInput.value = true
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code == '0') {
        if (form.value.payMth == 'A') {
          form.value.priceBase = response.data.data.priceCash
        } else {
          form.value.priceBase = response.data.data.priceBill
        }
        form.value.upriceLineId = response.data.data.id
        var endPrice = form.value.priceBase
        for (var i = 0; i < tableDataSettlement.value.length; i++) {
          for (var j = 0; j < salTransSciWeightedList.value.length; j++) {
            if (tableDataSettlement.value[i].settleItem == salTransSciWeightedList.value[j].sciProjectName)
              if (Number(salTransSciWeightedList.value[j].sciProjectNum) <= Number(tableDataSettlement.value[i].settleValueTo)
                  && Number(salTransSciWeightedList.value[j].sciProjectNum) >= Number(tableDataSettlement.value[i].settleValueFrom)) {
                var pr = (Number(salTransSciWeightedList.value[j].sciProjectNum) - Number(tableDataSettlement.value[i].referenceValue)) / Number(tableDataSettlement.value[i].settleSpan) * Number(tableDataSettlement.value[i].settleDiffer)
                endPrice += Math.round(pr * 100) / 100
              }
          }
        }
        form.value.invPrice = endPrice
        var amt = endPrice * form.value.qty
        form.value.invAmt = Math.round(amt * 100) / 100


      }
    })


  } else {
    ElMessage({
      type: 'warning',
      message: '请先选择结算信息！',
    })
  }
}

//20201112379 银
//20201112378 金
const priceAu = ref(0)
const getNewPriceAu = () => {
  var url = 'sal/UpriceLine/selectPriceByItemCdAndDateFw'
    var param = {
      itemCd:'20201112378',
      startDate: form.value.startDate,
      endDate: form.value.endDate,
    }
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code == '0') {
        priceAu.value = response.data.data.priceCash
        getNewPriceAg()
      }
    })
}
const priceAg = ref(0)
const getNewPriceAg = () => {
  var url = 'sal/UpriceLine/selectPriceByItemCdAndDateFw'
    var param = {
      itemCd:'20201112379',
      startDate: form.value.startDate,
      endDate: form.value.endDate,
    }
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code == '0') {
        priceAg.value = response.data.data.priceCash
        computeCuPrice()
      }
    })
}

const getNewPriceCu = () => {
  form.value.priceBase = ''
  form.value.invPrice = ''
  form.value.invAmt = ''
  if (form.value.payMth && form.value.itemCd) {
    LGInput.value = false
    // console.log(form.value)
    var url = 'sal/UpriceLine/selectPriceByItemCdAndDateFw'
    var param = {
      itemCd: form.value.itemCd,
      specType: form.value.specType,
      startDate: form.value.startDate,
      endDate: form.value.endDate,
    }
    if (form.value.itemNm == '铜精矿' || form.value.itemNm == '铜精矿2') {
      console.log(form.value)
      console.log(salTransSciWeightedList.value)
      proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
          console.log(response.data.data)
          form.value.priceBase = response.data.data.priceCash
          form.value.upriceLineId = response.data.data.id
          getNewPriceAu()
        }
      })
      
    } else {
      ElMessage({
        type: 'warning',
        message: '只支持铜精矿结算！'
      })
    }

  } else {
    ElMessage({
      type: 'warning',
      message: '请先选择结算信息！',
    })
  }
}

const headerData = ref()
const computeCuPrice = () => {
  var url = 'sal/UpriceLine/comupteCuPrice'
  var param = {
    agPrice: priceAg.value,
    auPrice: priceAu.value,
    priceBase: form.value.priceBase,
    salTransSciWeightedList: JSON.stringify(salTransSciWeightedList.value),
    tableDataSettlement: JSON.stringify(tableDataSettlement.value),
  }
  proxy.$axios.post(url,param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data.data)
      headerData.value = response.data.data
      form.value.invPrice = headerData.value.invPrice
      form.value.invAmt = headerData.value.invAmt
    }
  })
}

const LGInput = ref(false)
const height = ref(600)
const updateViewportHeight = () => {
  height.value = window.innerHeight * 0.65
  console.log(window.innerHeight);
};
onMounted(() => {
  getDicList()
  getTableData()
  updateViewportHeight()
  console.log(`the component is now mounted.`)
})
</script>

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

.el-form-item {
  width: 100%
}

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

</style>
