<template>
    <el-skeleton :rows="10" animated v-if="showSkeleton" />
    <div v-if="!showSkeleton">
      <el-card :body-style="cardBodyStyle">
        <el-form :inline="true" style="display: flex; align-items: center;">
          <el-form-item label="指示号" style="margin-right: 20px;" prop="tmsIndicate">
            <el-input v-model="queryForm1.tmsIndicate" placeholder="请输入指示号" clearable></el-input>
          </el-form-item>
          <el-form-item label="客户名称" style="margin-right: 20px;" prop="tradePartnerName">
            <el-input v-model="queryForm1.tradePartnerName" placeholder="请输入客户名称" clearable></el-input>
          </el-form-item>
          <div style="margin-left:20px;margin-top:-15px;">
            <el-button type="primary"   @click="dwQuery">查询</el-button>
          </div>

        </el-form>
      </el-card>
        <el-card :body-style="cardBodyStyle" class="diaClass90">
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="可制作" name="qb">
                    <el-card :body-style="cardBodyStyle">
                        <el-table style="width: 100%;max-height: 400px;overflow: auto;" :data="tableDataAll" border
                            :row-style="rowStyle">
                            <el-table-column type="index" label="序号" width="80" header-align="center" align="center"
                                show-overflow-tooltip>
                            </el-table-column>
                          <el-table-column v-if="true" prop="tmsIndicate" label="指示号" width="200" header-align="center" align="center"
                                           show-overflow-tooltip>
                          </el-table-column>

                          <el-table-column v-if="true" prop="tradePartnerName" label="客户名称" width="150" 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="100" header-align="center" align="center"
                                           show-overflow-tooltip>
                          </el-table-column>
                          <el-table-column label="收发货地" width="250" header-align="center" align="center" show-overflow-tooltip>
                            <template #default="scope">
                              {{ scope.row.toPlace}} -> {{ scope.row.fromPlace }}
                            </template>
                          </el-table-column>
                          <el-table-column prop="state" label="招标状态" width="120" header-align="center" align="center" show-overflow-tooltip>
                            <template #default="scope">
                              <span>{{ getStateText(scope.row.state) }}</span>
                            </template>
                          </el-table-column>
                          <el-table-column prop="bidManner" label="招标方式" width="120" header-align="center" align="center" show-overflow-tooltip>
                            <template #default="scope">
                              <span>{{ getBidMannerText(scope.row.bidManner) }}</span>
                            </template>
                          </el-table-column>


                          <el-table-column v-if="true" prop="validTime" label="有效时间" width="200" header-align="center"
                                           align="center" show-overflow-tooltip>
                          </el-table-column>
                          <el-table-column v-if="true" prop="bidCarr" label="中标承运商" width="200" header-align="center"
                                           align="center" show-overflow-tooltip>
                          </el-table-column>

                          <el-table-column label="操作" header-align="center" align="center" width="300px" fixed="right">
                                <template #default="scope">
                                    <el-button type="primary" plain @click="confirmPre(scope.row)">
                                      {{ getButtonText(scope.row.state) }}
                                    </el-button>
                                  <el-button plain type="warning" @click="handleEdit(scope.row)">选择</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                    <el-card :body-style="cardBodyStyle">
                        <div style="display: flex;width: 100%;align-items: center;">
                            <el-pagination v-model:current-page="currentPageAll" v-model:page-size="pageSizeAll"
                                :page-sizes="[20, 40, 60, 80]" :background="background"
                                layout="total, sizes, prev, pager, next, jumper" :total="totalAll"
                                @size-change="handleSizeChangeAll" @current-change="handleCurrentChangeAll" />

                        </div>
                    </el-card>
                </el-tab-pane>

                <el-tab-pane label="不可制作" name="drc">
                    <el-card :body-style="cardBodyStyle">
                        <el-table style="width: 100%;max-height: 400px;overflow: auto;" :data="tableDataDrc" border
                            :row-style="rowStyle">
                          <el-table-column type="index" label="序号" width="80" header-align="center" align="center"
                                           show-overflow-tooltip>
                          </el-table-column>
                          <el-table-column v-if="true" prop="tmsIndicate" label="指示号" width="200" header-align="center" align="center"
                                           show-overflow-tooltip>
                          </el-table-column>
                          <el-table-column v-if="true" prop="tradePartnerName" label="客户名称" width="150" 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="100" header-align="center" align="center"
                                           show-overflow-tooltip>
                          </el-table-column>
                          <el-table-column label="收发货地" width="250" header-align="center" align="center" show-overflow-tooltip>
                            <template #default="scope">
                              {{ scope.row.toPlace}} -> {{ scope.row.fromPlace }}
                            </template>
                          </el-table-column>



                        </el-table>
                    </el-card>
                    <el-card :body-style="cardBodyStyle">
                        <div style="display: flex;width: 100%;align-items: center;">
                            <el-pagination v-model:current-page="currentPageAll" v-model:page-size="pageSizeAll"
                                :page-sizes="[20, 40, 60, 80]" :background="background"
                                layout="total, sizes, prev, pager, next, jumper" :total="totalDrc"
                                @size-change="handleSizeChangeAll" @current-change="handleCurrentChangeAll" />
                            <!-- &nbsp &nbsp &nbsp &nbsp &nbsp <p
                                    style="height: 25px;width: 25px;background-color: rgb(188, 216, 190);"></p>
                                &nbsp已发货&nbsp &nbsp -->
                        </div>
                    </el-card>
                </el-tab-pane>



            </el-tabs>

        </el-card>


      <el-dialog :close-on-click-modal="false" draggable title="招标方式" v-model="dialogVisible" width="1450px"
                 top="5vh"  @open="openDialog">
            <el-card :body-style="cardBodyStyle">
              <template #header>
              <el-form :model="form" label-width="200px" label-position="right" inline ref="ruleFormRef" :rules="rules">
                <el-form-item label="指示号"  >
                  <el-input v-model="form.tmsIndicate" :disabled="true" clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="招标名称">
                  <el-input v-model="form.tenderName" :disabled="true"  clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="计划量">
                  <el-input v-model="form.qty" :disabled="true"  clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="合同号"  >
                  <el-input v-model="form.contrNo"  :disabled="true" clearable style="width: 200px"></el-input>
                </el-form-item>

                <el-form-item label="发货地址"  >
                  <el-input v-model="form.toPlace"  :disabled="true" clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="收获地址"  >
                  <el-input v-model="form.fromPlace"  :disabled="true" clearable style="width: 200px"></el-input>
                </el-form-item>

                <el-form-item label="接货人"  >
                  <el-input v-model="form.rece"  :disabled="true" clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="开标日期"  prop="bidDate" >
                  <el-date-picker v-model="form.bidDate"  type="datetime" style="width: 200px;"
                                  ></el-date-picker>
                </el-form-item>
                <el-form-item label="截标日期" prop="endBidDate" >
                  <el-date-picker v-model="form.endBidDate"  type="datetime" style="width: 200px;"
                                 ></el-date-picker>
                </el-form-item>
                <el-form-item label="接货人电话"  >
                  <el-input v-model="form.receNumber"  :disabled="true" clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="招标要求"  >
                  <el-input v-model="form.tenderRequest" type="textarea"  clearable style="width: 300px"></el-input>
                </el-form-item>
              </el-form>
          </template>

                <el-form-item label="招标方式"  >
                    <el-radio-group v-model="form.bidManner" @change="handleBidTypeChange">
                    <el-radio label="0">公开招标</el-radio>
                    <el-radio label="1">邀标</el-radio>
                  </el-radio-group>
                </el-form-item>

              <div v-if="form.bidManner =='1'&& showCarriersTable">
                <el-table
              ref="testTable"
                    :data="carriers"
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
                    :row-class-name="tableRowClassName"
                >
                  <el-table-column type="selection"  width="55"></el-table-column>
                  <el-table-column prop="ftranscode" label="承运商名称" width="180"></el-table-column>
                  <el-table-column prop="ftransname" label="承运商代码" width="180"></el-table-column>
                  <el-table-column prop="ftransdirector" label="承运商负责人" width="180"></el-table-column>
                  <el-table-column prop="ftransdirectorphone" label="联系电话" width="180"></el-table-column>
                </el-table>

              </div>
             <Attachment ref="AttachmentRefTender" :fId="fId"></Attachment>

              <template #footer>
                <div class="dialog-footer" style="margin-left: 1000px" >
                  <el-button type="success" :disabled="isSaveDisabled" @click="handleSave1">保存</el-button>
                  <el-button type="success" :disabled="isDisabledfb"@click="handleSave(ruleFormRef)">发布</el-button>
                  <el-button type="danger" @click="handleSave2">作废</el-button>
                  <el-button type="danger" @click="handleCancelSave1">取消</el-button>
                </div>
              </template>

            </el-card>

        </el-dialog>

      <el-dialog
          :close-on-click-modal="false"
          draggable
          v-model="dialogVisible1"
          width="1000px"
          top="18vh">
        <template #title>
          <div class="dialog-title">
            选择承运商报价
            <span class="warning-text"></span>
          </div>
        </template>
        <el-card :body-style="cardBodyStyle">
          <template #header>
            <el-form :inline="true" style="display: flex; align-items: center;">
              <el-form-item label="承运商编码" style="margin-right: 20px;" prop="carrNum">
                <el-input v-model="formBidActive.carrNum" placeholder="请输入承运商编码" clearable></el-input>

              </el-form-item>
              <el-form-item label="承运商名称" style="margin-right: 20px;" prop="carrName">
                <el-input v-model="formBidActive.carrName" placeholder="请输入承运商名称" clearable></el-input>
              </el-form-item>
              <div style="margin-left:20px;margin-top:-15px;">
                <el-button type="primary"   @click="cysQuery">查询</el-button>
                <el-button type="danger"  :disabled="isDisabled" @click="requotes">重新报价</el-button>
              </div>
            </el-form>
            <div style="font-size: 12px; color: #e83511; margin-top: 5px;">
              总计划量:  {{ form.qty }}，拆分剩余量:{{ remainingQuantity }}
            </div>
          </template>
          <!--              @current-change="handleChange"-->
          <el-table
              :data="tableDataBidActive"
              border
              @selection-change="handleSelectionChangeZb"
              ref="tableRef"
          >
            <el-table-column type="selection" width="55" :selectable="selectable"></el-table-column>
            <el-table-column type="index" label="序号" align="center" width="60">
              <template #default="scope">
                <span>{{ scope.$index + (currentPage1 - 1) * pageSize1 + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="true" prop="tmsTender" label="物流招标号" width="200"
                             header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="carrNum" label="承运商编码" width="180"
                             header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>

            <el-table-column v-if="true" prop="carrName" label="承运商名称" width="180"
                             header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column v-if="true" prop="quoteAmount" label="报价金额" width="180"
                             header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="quote" label="分配任务量" width="180" header-align="center" align="center" show-overflow-tooltip>
              <template v-slot="{ row }">
                <el-input
                    v-model="row.rwl"
                    placeholder="请分配任务量"
                    :disabled="!row.showRwlInput"
                ></el-input>
              </template>
            </el-table-column>

            <el-table-column prop="" label="报价文件" header-align="center" align="center" width="200px">
              <template #default="scope">
                <el-button type="text" @click="handlePreview(scope.row)">报价文件</el-button>
              </template>
            </el-table-column>

          </el-table>
        </el-card>

        <el-card :body-style="cardBodyStyle">
          <el-pagination  :current-page="currentPage1"  :page-size="pageSize1" :page-sizes="pageSizes1"
                          :total="totalRows1" background="background" layout="total, sizes, prev, pager, next, jumper"
                          @size-change="handleSizeChange1" @current-change="handleCurrentChange1">
          </el-pagination>
        </el-card>
        <div v-if="showAttachment">
          <span>
            报价文件
          </span>
          <el-button  type="text" @click="closeAttachment">关闭</el-button>
          <Attachment ref="AttachmentRefBidding" :fId="fId" :upload-button="false"></Attachment>
        </div>
        <div>
          <p v-if="form.bidCarr">
            选中的承运商是: <span style="color: red;">{{ form.bidCarr }}</span>
          </p>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="success" @click="handleSaveByxb" :disabled="isButtonDisabled">保存</el-button>
            <el-button type="danger" @click="handleCancelSave">取消</el-button>
          </div>
        </template>
      </el-dialog>


    </div>
</template>

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

const viewa = ref(import.meta.env.VITE_BASE_API)

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
import { ElMessage } from 'element-plus';
import Attachment from "@/components/Attachment.vue";
import { computed } from 'vue';
/**
 * 查看图片
 */
//查询数据（图片id）
const listPic = ref([])
const tableDataPic = ref([])
const showViewer = ref(false);
const initialIndex = ref(0);
const previewList = ref([]);
// 获取表格引用
const multipleTable = ref(null);

const AttachmentRefTender = ref(null)
const tableRef = ref(null);


const showAdditionalColumn = ref(false);
// 计算剩余量
const remainingQuantity = computed(() => {
  if (form.value.bidCarr){
    return '已拆分完毕'
  }
  const totalAssigned = tableDataBidActive.value.reduce((sum, row) => sum + (parseFloat(row.rwl) || 0), 0);
  return form.value.qty - totalAssigned;
});
const toggleAdditionalColumn = () => {
  showAdditionalColumn.value = !showAdditionalColumn.value;
};
const getStateText = (state) => {
  switch (state) {
    case '0':
      return '保存';
    case '1':
      return '已发布';
    case '2':
      return '截标';
    case '9':
      return '作废';
    default:
      return '';
  }
};
const getButtonText = (state) => {

  return state === '1' ? '查看' : '招标';
};
const getBidMannerText = (bidManner) => {
  switch (bidManner) {
    case '0':
      return '公开招标';
    case '1':
      return '邀标';

    default:
      return '';
  }
};
const carriers = ref([]);
const showCarriersTable = ref(true);

const querycarriers =ref({
  ftranscode:'',
  ftransname:''

})

const selectedCarriers = ref([]);
const handleSelectionChange = (selection) => {

  selectedCarriers.value = selection;

}
const isButtonDisabled = computed(() => {

  return !!form.value.bidCarr; // 如果 form.bidcarr 有值，则按钮禁用
});

const handleBidTypeChange = (value) => {
  carriers.value = []
    var url = 'tms/Carrier/queryNoPage'
    var param = {
      params: JSON.stringify(querycarriers.value)
    }
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code == '0') {
        carriers.value = response.data.data

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

}
const handleBidTypeChange2 = (value) => {
  carriers.value = []
    var url = 'tms/Carrier/queryNoPage'
    var param = {
      params: JSON.stringify(querycarriers.value)
    }
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code == '0') {
        carriers.value = response.data.data

        showCarriersTable.value=true

        if(form.value.tmsTender!=null && form.value.tmsTender!=undefined) {
          BidListquery.value.tmsTender = form.value.tmsTender
          var url = 'tms/BidList/queryNoPage'
          var param = {
            params: JSON.stringify(BidListquery.value)
          }
          proxy.$axios.get(url, param).then(response => {
            if (response.data.code == '0') {
              BidList.value = response.data.data;
              selectedCarriersFromDB.value = BidList.value.map(item => item.carrNum
              );
              if (Array.isArray(selectedCarriersFromDB.value)) {
                carriersTable.value = carriers.value.filter(carrier => selectedCarriersFromDB.value.includes(carrier.ftranscode));
              }
              const matchedRow = carriers.value.filter(item => BidList.value.some(carrier => carrier.carrNum === item.ftranscode));
              matchedRow.forEach(row => {
                testTable.value.toggleRowSelection(row, true);
              });
              // setTimeout(() => {
              //   matchedRow.forEach(row => {
              //     testTable.value.toggleRowSelection(row, true);
              //   });
              // }, 1000);
              console.log(matchedRow)

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

}
const selectedCarriersFromDB = ref([]);
const confirmPre = (row) => {
  dialogVisible.value = true
  form.value=row;
  console.log(row.state)
  if (row.state ==null|| row.state ==undefined || row.state ==''){
    isSaveDisabled.value=false
  }else if(row.state !='0'){
    isSaveDisabled.value=true
  }

  if (form.value.bidManner=='1'){
    //查询承运商
    handleBidTypeChange2()
    if(form.value.tmsTender!=null && form.value.tmsTender!=undefined){
      BidListquery.value.tmsTender=form.value.tmsTender
      //邀请名单--回显承运商
     // BidListqueryNoPage();
    }
  }
  fId.value=row.tmsIndicate;

}
const BidListquery =ref({
  tmsTender:''

})
const BidList=ref([])
const carriersTable= ref([]);
const BidListqueryNoPage =  () => {

  var url = 'tms/BidList/queryNoPage'
  var param = {
    params: JSON.stringify(BidListquery.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      BidList.value = response.data.data;
      selectedCarriersFromDB.value = BidList.value.map(item => item.carrNum
      );
      if (Array.isArray(selectedCarriersFromDB.value)) {
        carriersTable.value = carriers.value.filter(carrier => selectedCarriersFromDB.value.includes(carrier.ftranscode));

      }
      // 找到匹配的行并选中


      // if (testTable.value){
      //   testTable.value.clearSelection()
      // }

      const matchedRow = carriers.value.filter(item => BidList.value.some(carrier => carrier.carrNum === item.ftranscode));
      // matchedRow.forEach(row => {
      //   testTable.value.toggleRowSelection(row , true);
      // });
      // for( var i = 0 ; i < matchedRow.length ; i++){
      //   testTable.value.toggleRowSelection(matchedRow[i]);
      // }
      setTimeout(() =>{
        matchedRow.forEach(row => {
          testTable.value.toggleRowSelection(row , true);
        });
      }, 1000);
      console.log(matchedRow)

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

const tableRowClassName = ({ row }) => {
  const isRowSelected = selectedCarriersFromDB.value.includes(row.ftranscode);

  return isRowSelected ? 'highlight-row' : '';
};
/**
 * 第一行
 */
const isSaveDisabled = ref(false);
const activeName = ref('qb')

const handleClick = (tab, event) => {
    //每次点击标签都会回到第一页

    currentPageAll.value = 1
    queryAll()
}
/**
 * 所属类目配置
 */
onMounted(() => {
    queryAll()
  handleBidTypeChange()
  BidListqueryNoPage()


})
const localStorageDeptTree = ref('')
const deptName = ref('')
const deptCode = ref('')
const deptid = ref('')


/**
 *   查询
 */

/**
  * 详情
*/
const xqRc = ref([])
const dialogVisible = ref(false)
const dialogVisible2 = ref(false)
const form = ref({
  id:'',
  tmsIndicate: '',
  tradePartnerName: '',
  contrNo: '',
  itemNm: '',
  qty: '',
  fother: '',
  tenderName:'',
  tenderRequest:'',
  bidDate:'',
  endBidDate:'',
  rece:'',
  receNumber:'',
  state:'',
  bidManner:'',
  traffic:'',
  tranMaterial:'',
  relePlan:'',
  releContract:'',
  toPlace:'',
  receipt:'',
  origin:'',
  fromPlace:'',
  quateFrequency:'',
  bidCarr:''
})

const fId = ref('x')




const tableDataAll = ref([])
const tableDataDrc = ref([])
const tableDataZc = ref([])
const tableDataCc = ref([])

const dwQuery = () => {
    currentPageAll.value = 1
    queryAll()
}
const queryForm1 = ref({
  tradePartnerName: '',
  tmsIndicate: '',
  delvMth:''
})

const queryAll = () => {
  var url = 'tms/Tender/queryAlljh'
  var param = {
    page: currentPageAll.value,
    pageSize: pageSizeAll.value,
    activeName: activeName.value,
    json: JSON.stringify(queryForm1.value)
  }

  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      //全部数据
      tableDataAll.value = response.data.data.list
      console.log(tableDataAll.value)
      totalAll.value = response.data.data.total
      tableDataDrc.value = response.data.data.listDrc
      totalDrc.value = response.data.data.totalDrc
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const ruleFormRef = ref()
const rules = reactive({
  bidDate: [{
    required: true,
    message: '请选择开标日期',
    trigger: 'change'| 'blur'
  }],
  endBidDate: [{
    required: true,
    message: '请选择开标日期',
    trigger: 'change'| 'blur'
  }],

})

const handleSave = (ruleFormRef) => {
  ruleFormRef.validate((valid, fields) => {
  form.value.releContract = form.value.contrNo;
  form.value.relePlan = form.value.tmsIndicate;
  form.value.origin = form.value.toPlace;
  form.value.receipt = form.value.fromPlace;
    form.value.traffic = form.value.qty;
  form.value.state='1';
    form.value.tranMaterial=form.value.itemNm
    if (form.value.bidManner==''||form.value.bidManner==null){
      ElMessage({
        message: '请选择招标方式',
        type: 'error',
      })
      return
    }

    if (valid) {
      var url = 'tms/Tender/save'
      var param = {

        carriers: selectedCarriers.value,
        form : form.value
      }
      proxy.$axios.post(url, param,"application/json; charset=utf-8").then(response => {
        if (response.data.code == 0) {

          console.log(form.value)
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          isSaveDisabled.value = true;
          AttachmentRefTender.value.upload()
          queryAll()

          dialogVisible.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}
const currentRow = ref(null);
const handleChange = (row)=>{
  currentRow.value=row;
  console.log(currentRow.value)
}

const multipleSelection = ref([])
const handleSelectionChangeZb = (selection) => {
  console.log(tableDataBidActive)
  tableDataBidActive.value.forEach(row => {
    // 如果当前行在选中列表中，则允许编辑；否则不允许编辑
    row.showRwlInput = selection.includes(row);
    if (!row.showRwlInput) {
      row.rwl = '';  // 清空输入
    }
  });
  multipleSelection.value = selection
  console.log(multipleSelection.value)
};
const selectable = (row, index) => {
  // 默认所有行都可以被选中
  return true;
};
function isValidNumber(value) {
  return !isNaN(value) && !isNaN(parseFloat(value)) && value.trim() !== '';
}
const handleSaveByxb = () => {

  if ( multipleSelection.value.length < 1) {
    ElMessage({
      message: '请至少选择一行数据',
      type: 'warning'
    });
    return;
  }

  if (remainingQuantity.value !=0){
    ElMessage({
      message: '请彻底拆分计划数量',
      type: 'warning'
    });
    return;
  }
  for (const item of multipleSelection.value) {
    const rlwValue = item.rwl;
    console.log(rlwValue)

    // 确保 rlwValue 是一个字符串
    if (typeof rlwValue !== 'string') {
      ElMessage({
        message: 'rlw 属性必须是字符串类型',
        type: 'error'
      });
      return;
    }

    // 清除首尾空格
    const trimmedRlwValue = rlwValue.trim();

    // 检查 rlw 是否为有效数字
    if (!isValidNumber(trimmedRlwValue)) {
      ElMessage({
        message: '请输入有效数字',
        type: 'error'
      });
      return;
    }
  }

  ElMessageBox.confirm(
      '请确认是否要选中此承运商，保存后无法修改。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {


    var url = 'tms/BidActive/BidUpdate';
    var param = {
    json: JSON.stringify(multipleSelection.value)
    };
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == 0) {
        ElMessage({
          message: '保存成功',
          type: 'success',
        });
        queryAll();
        dialogVisible1.value = false;
      } else {
        ElMessage({
          message: '操作失败' + response.data.msg,
          type: 'error'
        });
      }
    }).catch(error => {
      ElMessage({
        message: '请求错误: ' + error.message,
        type: 'error'
      });
    });
  }).catch(() => {
    // 用户点击了取消按钮后的处理逻辑
    ElMessage({
      type: 'info',
      message: '已取消保存'
    });
  });
};

const handleSave1 = () => {
  form.value.releContract = form.value.contrNo;
  form.value.relePlan = form.value.tmsIndicate;
  form.value.origin = form.value.toPlace;
  form.value.receipt = form.value.fromPlace;
  form.value.traffic = form.value.qty;
  form.value.tranMaterial=form.value.itemNm
  form.value.state='0';

  var url = 'tms/Tender/save'
      var param = {

        carriers: selectedCarriers.value,
        form : form.value
      }
      proxy.$axios.post(url, param,"application/json; charset=utf-8").then(response => {
        if (response.data.code == 0) {


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


}
const handleSave2 = () => {
  form.value.releContract = form.value.contrNo;
  form.value.relePlan = form.value.tmsIndicate;
  form.value.origin = form.value.toPlace;
  form.value.receipt = form.value.fromPlace;
  form.value.traffic = form.value.qty;
  form.value.tranMaterial=form.value.itemNm
  form.value.state='9';


  var url = 'tms/Tender/save'
  var param = {

    carriers: selectedCarriers.value,
    form : form.value
  }
  proxy.$axios.post(url, param,"application/json; charset=utf-8").then(response => {
    if (response.data.code == 0) {

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

/**
  * 触发确认
  */


/**
 * 分页
 */
const currentPageAll = ref(1)
const totalAll = ref(0)
const totalDrc = ref(0)
const totalZc = ref(0)
const totalCc = ref(0)
const pageSizeAll = ref(20)
const handleSizeChangeAll = (val) => {
    pageSizeAll.value = val
    queryAll()
}
const handleCurrentChangeAll = (val) => {
    currentPageAll.value = val
    queryAll()
}
const currentPage1 = ref(1)
const totalRows1 = ref(0)
const pageSizes1 = ref([5, 10, 20, 30, 40])
const pageSize1 = ref(5)
const handleSizeChange1 = (val) => {
  pageSize1.value = val
  getTableBidActive()
}
const handleCurrentChange1 = (val) => {
  currentPage.value = val
  getTableBidActive()
}
const cysQuery = () => {
  currentPage1.value = 1
  getTableBidActive()
}
const query = ref({
  tenderName:'',
  carrName:'',
  carrNum:''
})
const tableDataBidActive = ref([])
const handleCancelSave = () => {
  dialogVisible1.value = false
}
const handleCancelSave1 = () => {
  dialogVisible.value = false
}
const tableData = ref([])
const closeAttachment = () => {
  showAttachment.value = false;
  fId.value = ''; // 清空 fId
};
const dialogVisible1 = ref(false)
const handleEdit = (row) => {
  currentPage1.value-1
  dialogVisible1.value = true
  showAttachment.value = false;
  fId.value=''
  formBidActive.value.tmsTender = row.tmsTender
  formBidActive.value.quateFrequency = row.quateFrequency
  form.value=row;

  getTableBidActive()
}

const getTableBidActive = () => {

  var url = 'tms/BidActive/query'
  var param = {
    page: currentPage1.value,
    rows: pageSize1.value,
    params: JSON.stringify(formBidActive.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      const recordsWithShowRwlInput = response.data.data.records.map(record => ({
        ...record,
        showRwlInput: false
      }));
      tableDataBidActive.value =recordsWithShowRwlInput
      totalRows1.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const formBidActive = ref({
  TenderId:'',
  tmsTender:'',
  carrNum:'',
  carrName:'',
  quateFrequency:''
})

const showAttachment = ref(false);
const handlePreview = (row) => {
  if (showAttachment.value) {
    // 如果已经显示预览，则关闭预览
    showAttachment.value = false;
  } else {
    // 否则显示预览
    showAttachment.value = true;
    fId.value = row.tmsTender + row.carrNum;
  }
};

const testTable = ref(null)

const isDisabled = computed(() => {
  const now = new Date();
  const endtime = new Date(form.value.endBidDate);

  if (form.value.bidCarr) {
    return true;
  }
  // 如果 bidCarr 不存在，则根据时间判断是否禁用
  return endtime <= now; // 注意这里比较符的方向
})
const isDisabledfb = computed(() => {
  if (form.value.bidCarr){
    return true
  }
  return false;
})

const requotes = () => {
  // 弹出确认对话框

  if (form.value.quateFrequency==null && form.value.quateFrequency=='' ){
    ElMessage({
      message: '请先做标',
      type: 'error'
    });
    dialogVisible1.value = false;
    dialogVisible.value = true;
    return
  }
  ElMessageBox.confirm(
      '您是否对本次报价不满意，要重新进行报价？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 用户点击确定后执行的逻辑
    var url = 'tms/Tender/UpdateRequotes';
    var param = {
      json: JSON.stringify(form.value),
    };
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == 0) {
        form.value = response.data.data;
        ElMessage({
          message: '保存成功',
          type: 'success',
        });
        queryAll()
        dialogVisible1.value = false;
      } else {
        ElMessage({
          message: '操作失败' + response.data.msg,
          type: 'error'
        });
      }
    }).catch(error => {
      ElMessage({
        message: '网络请求错误',
        type: 'error'
      });
    });
  }).catch(() => {
    // 用户点击取消后执行的逻辑
    ElMessage({
      message: '已取消重新报价',
      type: 'info'
    });
  });
}




</script>

<style scoped>


::v-deep .highlight-row {
  background-color: #e1e0e0 !important; /* 使用 !important 确保样式优先级 */
}
::v-deep .el-table__body tr.current-row {
  background-color: #e1b3f1 !important; /* 你可以选择任何你喜欢的颜色 */
}
/* 如果需要改变文字颜色，也可以在这里定义 */
::v-deep .el-table__body tr.current-row td {
  color: #21012d !important; /* 文字颜色 */
}


</style>