<template>
  <div>

  <SearchBox ref="SearchBoxRef" formName="inputQuery" :formData="query" @PopupNo="PopupNo" @reset="reset"></SearchBox>
    <el-card :body-style="cardBodyStyle">
      <el-form-item style="margin-bottom: 0px;">
        <el-button plain type="primary" @click="handleSearch">查询</el-button>
        <el-button plain type=" " @click="CancelSearch">取消</el-button>
      </el-form-item>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-tabs v-model="activeNameTop" type="border-card">
        <el-tab-pane label="订单" name="master">
          <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChangeHand"
            @row-click="DoubleClick">
            <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="contrNo" label="合同号" width="200" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
              <!--合同行号=订单号      -->
            <el-table-column v-if="true" prop="purOrdNo" label="订单号" width="200" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>

            <el-table-column v-if="true" prop="itemNm" label="物料名称" width="200" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>

            <el-table-column v-if="true" prop="supplierNm" label="客户" width="200" header-align="center"
              align="center" show-overflow-tooltip>
            </el-table-column>

            <el-table-column v-if="true" prop="qty" label="数量合计" width="100" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="allWeight" label="完成量" width="100" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="addTime" label="生成时间" width="300" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作" header-align="center" align="center" width="200" fixed="right">
              <template #default="scope">
                <el-button plain type="warning" @click="handDetailed(scope.row)">详细</el-button>
                <el-button plain type="warning" @click="tracking1(scope.row)">跟踪</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <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" style="margin-top: 10px">
        </el-pagination>
      </el-tabs>
    </el-card>
    <el-card :body-style="cardBodyStyle" >

        <el-form :inline="true" :model="query">
          <el-row>
            <el-col :span="5">
              <el-form-item label="指示号">
                <el-input v-model="query.dordNo" >
                  <template #append>
                    <el-button :icon="Search" @click="handleLine" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="物流状态">
                <Selector :value="query.tmsFlag" :width="200"  dicType="TMS_FLAG" @change="typeChange4">
                </Selector>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>


      <el-tabs v-model="activeNameBottom" type="border-card">
        <el-tab-pane label="发货指示" name="first">


          <el-table :data="tableDataLine" @cell-dblclick="tableEdit" border highlight-current-row v-loading="loadingLine">
            <!-- <el-table-column type="selection" fixed></el-table-column> -->

            <el-table-column v-if="true" prop="dordNo" label="指示号" width="140" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>


            <el-table-column v-if="true" prop="itemNm" label="物料名称" width="150" header-align="center" align="center"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="qty" label="计划重量" width="120" 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"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="finWeight" label="完成重量" width="120" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>

            <el-table-column v-if="true" prop="tmsMateSurp" label="剩余重量" width="120" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="arrCar" label="到达车辆" width="120" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="dayFinWeight" label="当日完成重量" width="120" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="dayFinCar" label="当日完成车数" width="120" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="nowCar" label="在途车数" width="120" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>

            <el-table-column v-if="true" prop="carriers" label="承运商" width="120" header-align="center" align="center"
                             show-overflow-tooltip>
              <template v-slot="scope">
                <el-button v-if="TmsWaybill.length==0" class="assign-button" type="primary"  link @click="assign(scope.row)">{{ scope.row.carriers }}</el-button>
                <span v-else>{{ scope.row.carriers }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="false" prop="ftranscode" label="承运商编码" width="120" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="tmsMateIfSamp" label="是否采样" width="120" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="dateRange" label="有效时间" width="250" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="tmsFlag" label="物流状态" width="120" header-align="center"  fixed="right" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作" header-align="center" align="center" width="200" fixed="right">
              <template #default="scope">

                <el-button plain type="warning" @click="tracking2(scope.row)">跟踪</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog class="diaClass" :close-on-click-modal="false" draggable title="订单详情" v-model="dialogHandValue" width="80%"
               top="5vh" @open="openDialog">
      <el-card class="box-card">
        <!-- <el-tag>基本信息</el-tag> -->
        <!-- <el-button type="success" @click="handleSave(ruleFormRef)" size="small"
          style="margin-left: 10px;">保存</el-button> -->

        <el-form :model="form" label-width="110px" label-position="right" inline ref="ruleFormRef" :rules="rules"
                 style="margin-top: 10px;">
          <el-row>

            <el-col :span="6">
              <el-form-item label="合同名称">
                <el-input v-model="form.contrNm" clearable disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同号" prop="contrNo">
                <el-input v-model="form.contrNo" clearable disabled>

                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同日期">
                <el-date-picker v-model="form.contrDt" type="date" value-format="YYYY-MM-DD" clearable disabled style="width: 100%"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商" prop="tradePartnerName">
                <el-input v-model="form.supplierNm" clearable disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商编码" prop="tradePartnerCode">
                <el-input v-model="form.supplierCd" clearable disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="交货方式">
                <el-input v-model="form.delvMth" clearable disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="运输方式">
                <el-input v-model="form.trsMth" clearable disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="对方合同号">
                <el-input v-model="form.khContrNo" clearable disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="数量合计">
                <el-input v-model="form.qty" clearable disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同金额">
                <el-input v-model="form.totalAmt" clearable disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </el-dialog>

    <el-dialog class="diaClass" :close-on-click-modal="false" draggable title="车辆运输详情" v-model="dialogVisible" width="61.5%"
               top="5vh" @open="openDialogM">
      <el-card class="box-card">
        <el-table :data="formMeasure" stripe border height="300"
                  :default-sort="{ prop: 'purOrdNo', order: 'descending' }" style="width: 99%;">

          <el-table-column  prop="orderid" sortable label="订单号" width="120" header-align="center" align="center"
                           show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="ywh" sortable label="运单号" width="120" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="fhdwmc" sortable label="客商名称" width="120" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="mzh" sortable label="实际毛重(t)" width="150" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="pzh" sortable label="实际皮重(t)" width="150" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="jzh" sortable label="实际净重(t)" width="150" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="crossTime" sortable label="计毛时间" width="120" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="tareTime" sortable label="计皮时间" width="120" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
        </el-table>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="handleExport">导出</el-button>
          <el-button type="danger" plain @click="handleCancelSave">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog class="diaClass" :close-on-click-modal="false" draggable title="指派承运商" v-model="dialogQchVisible" width="40%"
               top="5vh" @open="openDialogQch"  >
      <el-card :body-style="cardBodyStyle">
        <el-form :inline="true" :model="carrierQuery" label-position="right" label-width="100px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="承运商名称" prop="qchNm">
                <el-input v-model="carrierQuery.ftransname" style="width: 220px;" clearable>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="负责人" prop="qchfz">
                <el-input v-model="carrierQuery.ftransdirector" style="width: 220px;" clearable>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-button plain type="primary" @click="getMeasureSeach" style="margin-left: 15px;">查询</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="formQch" border highlight-current-row @row-click="handleSelectionChange" :default-sort="{ prop: 'qchCode', order: 'descending' }" >
          <el-table-column type="index" label="序号" align="center" width="60" >
            <template #default="scope">
              <span>{{ scope.$index + (currentPageCotHead - 1) * pageSizeCotHead + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column  prop="ftranscode" sortable label="承运商编码" width="120" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="ftransname" sortable label="承运商名称" width="150" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="ftransdirector" sortable label="负责人" width="120" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>
          <el-table-column  prop="ftransdirectorphone" sortable label="联系方式" width="200" header-align="center" align="center"
                            show-overflow-tooltip>
          </el-table-column>

        </el-table>
        <el-pagination @size-change="handleSizeChangeCotHead" @current-change="handleCurrentChangeCotHead"
                       :current-page="currentPageCotHead" :page-sizes="pageSizesCotHead" :page-size="pageSizeCotHead"
                       layout="total, sizes, prev, pager, next, jumper" :total="totalRowsCotHead" style="margin-top: 10px" >
        </el-pagination>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="handleSave">保存</el-button>
          <el-button type="danger" plain @click="handleQchCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'

import {
  ref,
  reactive,
  onActivated,
  onMounted,
  getCurrentInstance
} from 'vue'
import { Search } from '@element-plus/icons-vue'

const {
  proxy
} = getCurrentInstance()

import tools from '@/tools'
import Selector from "@/components/Selector.vue";
import SearchBox from "@/components/SearchBox.vue";
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
  handleSearch()
})

const handleQchCancelSave = () => {
  dialogQchVisible.value=false
}
/**
 *   查询
 */
const query = ref({
  contrNo: '',
  khContrNo: '',
  supplierNm :'',
  conSts:'',
  tmsFlag:'',
  purOrdNo:'',
  dordNo:''


})

//指派业务
const dialogQchVisible = ref(false)
const formQch = ref([])
//拿到行数据
const Instructions = ref({

})
//查询字段
const carrierQuery = ref({
  ftransname:'',
  ftransdirector:''
})
//拿到承运商字段
const carrierData = ref({
})
const handleSelectionChange = (val) => {

  carrierData.value = val
  console.log(carrierData.value)
}
const getMeasureSeach = () => {
  currentPageCotHead.value=1
  getTableqch()

}

const assign = (row) => {
  Instructions.value=row

  console.log(Instructions.value)
  dialogQchVisible.value=true

  getTableqch()
}
const handleSizeChangeCotHead = (val) => {
  pageSizeCotHead.value = val
  getTableqch()
}
const handleCurrentChangeCotHead = (val) => {
  currentPageCotHead.value = val
  getTableqch()
}
const currentPageCotHead = ref(1)
const totalRowsCotHead = ref(0)
const pageSizesCotHead = ref([5, 10, 20, 30, 40])
const pageSizeCotHead = ref(5)

//查询承运商表
const getTableqch = () => {

  console.log(Instructions.value)
  var url = 'tms/Carrier/query'
  var param = {
    page: currentPageCotHead.value,
    rows: pageSizeCotHead.value,

    params: JSON.stringify(carrierQuery.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      formQch.value = response.data.data.records
      totalRowsCotHead.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const handleSave = () => {

  if (carrierData.value.ftransname == undefined) {
    ElMessage({
      message: '请选择承运商',
      type: 'error'
    })
    return
  }

  Instructions.value.carriers=carrierData.value.ftransname
  Instructions.value.ftranscode=carrierData.value.ftranscode

  console.log(Instructions.value)
      var url = 'sal/Delv/save'
      var param = {
        json: JSON.stringify(Instructions.value),
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {


          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()
          dialogQchVisible.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

}

// 采购订单头
const activeNameTop = ref('master')
const tableData = ref([])

const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}
const CancelSearch = () => {
  query.value = {}
  handleSearch()
}
const handleLine = () => {
 getOrdertmsIndicateTable()
}
const getTableData = () => {
  var url = 'cot/Head/queryHandAndLineByTms'
  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 typeChange2 = (val) => {
  form.value.carriers = val
}
const typeChange3 = (val) => {
  form.value.tmsFlag = val
}
const typeChange4 = (val) => {
  query.value.tmsFlag = val
}
// 采购订单行
const activeNameBottom = ref('first')


const TmsWaybill = ref([])
const loadingLine = ref(false)

const DoubleClick = (row) => {
  // console.log(row.purOrdNo)
  // this.headId = row.purOrdNo
  getOrderLineTable(row)
  getTmsWaybillTable(row)


}
//采购订单头信息
const dialogHandValue = ref(false)

const handDetailed = (row) => {
  dialogHandValue.value = true
  form.value = row
  console.log(form.value)
}
//采购订单跟踪
const formMeasure=ref()
const queryMeasure=ref({

})



const LineAndHeadMsg = ref({
  purOrdNo :'',

  tmsIndicate :''

})

/*let purOrdLnArray = ref([]);*/
const tableDataLine = ref([])
const getOrderLineTable = (row) => {
  var url = 'sal/Delv/queryConLine'
  query.value.purOrdNo = row.purOrdNo
  query.value.contrNo=row.contrNo
  console.log(query.value)

  var param = {
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {

    tableDataLine.value = response.data.data
    /*purOrdLnArray.value=tableDataLine.value.map(item => item.purOrdLn);
    console.log(purOrdLnArray)*/

  });
}

const getTmsWaybillTable = (row) => {
  var url = 'tms/TmsWaybill/queryBypurOrdNo'
  var param = {

    params: JSON.stringify(row)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      // console.log(typeof response.data.data )
      // console.log(  response.data.data )
      TmsWaybill.value = response.data.data
console.log(TmsWaybill.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const handleExport = () => {
  var params = {
    orderid: LineAndHeadMsg.value.purOrdNo,
    ywh: LineAndHeadMsg.value.tmsIndicate
  }
  location.href = import.meta.env.VITE_BASE_API +'/wgt/excel/exportPur?params='+ encodeURIComponent(JSON.stringify(params))
  // var url = 'wgt/Qchjlxx/queryByPuroedNo'
}
const tracking1 = (row) => {

  dialogVisible.value = true
  //formMeasure.value=row
  //调个查询
  LineAndHeadMsg.value.purOrdNo=row.purOrdNo
  //指示号
LineAndHeadMsg.value.tmsIndicate=''

  console.log(LineAndHeadMsg.value)
  getMeasureDta()
}
const tracking2 = (row) => {

  dialogVisible.value = true
  //formMeasure.value=row
  //调个查询
  LineAndHeadMsg.value.purOrdNo=''
    LineAndHeadMsg.value.tmsIndicate = row.dordNo
  console.log(LineAndHeadMsg.value)
  getMeasureDta()
}

const getMeasureDta = () => {

  var url = 'wgt/Qchjlxx/queryByPuroedNo'
  var param = {
    params: JSON.stringify(LineAndHeadMsg.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      formMeasure.value = response.data.data

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

}

const getOrdertmsIndicateTable = (row) => {
  var url = 'sal/Delv/queryConLine'
  var param = {
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {

    //console.log(this.response)
    //console.log(id)
    tableDataLine.value = response.data.data
    //console.log(this.tableDataLine)
  });

}
/**
 *   查询
 */


/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const dialogVisible = ref(false)
const form = ref({
  purOrdNo: '',
  contrNo: '',
  contrNm: '',
  tradePartnerCode: '',
  tradePartnerName: '',
  deptCd: '',
  deptNm: '',
  contrDt: '',
  payMth: '',
  delvMth: '',
  delvDt: '',
  trsMth: '',
  remark: '',
  checkName: '',
  qty: '',
  invMth: '',
  khContrNo: '',
  taxAmount :'',
  qtyUpper :'',
  qtyLower:'',
  carriers :'',
  tmsFlag :'',
  purOrdLn :'',
  dateRange :''

})
const ruleFormRef = ref()
const rules = reactive({

})
const PopupNo = ()=>{
  console.log('PopupNo')
}

/**
 * 新增
 */


/**
 * 保存、修改、删除
 */
const openDialogQch = () => {
}
const openDialog = () => {
}
const openDialogM = () => {
}


const handleCancelSave = () => {
  dialogVisible.value = false
}
const handleEdit = (row) => {
  dialogVisible.value = true
  form.value = row
}



// 查询合同
const queryCotHead = ref({
  contrNo: '',
  contrNm: '',
  supplierNm: '',
  contrDt: '',
  khContrNo: '',
})

const cotHeadDialogVisible = ref(false)

const searchCotHead = () => {
  cotHeadDialogVisible.value = true
}

// 示例数据
// const inittableData = () => {
//   var list = []

//   for (var i = 0; i < 10; i++) {
//     var map = {
//       purOrdNo: "D2829374921738891233" + "_" + i,
//       salOrdStatus: "订单发货中" + "_" + i,

//       supplierId: "2839198" + "_" + i,
//       khContrNo: "10293739237821374675238" + "_" + i,
//       itemNm: "镀锌卷" + "_" + i,
//       itemCd: "2838BB" + "_" + i,
//       stlGrd: "钢种" + "_" + i,
//       specType: "0.28*1000" + "_" + i,
//       houdu: "0" + "_" + i,
//       dingchi: "0" + "_" + i,
//       storeId: "",
//       actQty: "",
//     }
//     list.push(map)
//   }
//   tableData.value = list


// }
// onMounted(() => {
//   inittableData()
//   console.log(`the component is now mounted.`)
// })
</script>

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

::v-deep .el-dialog__body {

  background-color: #F2F6FC;
}

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


}
</style>
