<template>
  <div class="contentList">
    <Input v-model="typesearchFilter.name" placeholder="请输入标题名称" style="width: 480px"></Input>

    <el-button type="primary" @click="changePage(1)">查询</el-button>

    <el-table v-loading="loading" :data="tabData.data" style="width: 100%; margin-top: 2em" border>
      <el-table-column label="序号" type="index" width="70" align="center"></el-table-column>
      <el-table-column label="发布时间" width="160" align="center">
        <template #default="scope">
          {{ moment(scope.row.addTime).format('yyyy-MM-DD hh:mm:ss') || '暂无' }}
        </template>
      </el-table-column>
      <el-table-column label="联系人" width="100" prop="contactName" align="center"></el-table-column>
      <el-table-column label="联系电话" width="120" prop="contactCell" align="center"></el-table-column>
      <el-table-column label="信息标题" prop="name" width="200"></el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <Tag color="orange" v-if="scope.row.status == 4">{{ publishStatus(scope.row.status) }}</Tag>
          <Tag color="green" v-if="scope.row.status == 3">{{ publishStatus(scope.row.status) }}</Tag>
          <Tag color="red" v-if="scope.row.status == 2">{{ publishStatus(scope.row.status) }}</Tag>
          <Tag color="blue" v-if="scope.row.status == 1">{{ publishStatus(scope.row.status) }}</Tag>
          <Tag color="skyblue" v-if="scope.row.status == 5">{{ publishStatus(scope.row.status) }}</Tag>
        </template>
      </el-table-column>
      <el-table-column label="牛只分类" width="200">
        <template #default="scope">
          {{ scope.row.classifyOneName }}/{{ scope.row.classifyTwoName }}/{{ scope.row.classifyThreeName }}
        </template>
      </el-table-column>
      <el-table-column label="牛只规格重量" prop="weight" min-width="120">
        <template #default="scope">
          <Tag color="blue">{{ scope.row.weight }}</Tag>
        </template>
      </el-table-column>
      <el-table-column prop="buyPrice" label="意向价格" align="center" min-width="120">
        <template #default="scope">
          <b style="color: red">{{ scope.row.price }}</b>
        </template>
      </el-table-column>
      <el-table-column label="销售数量" min-width="120" align="center">
        <template #default="scope">
          {{ scope.row.count }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="牛只图片" align="center" width="120">
        <template #default="scope">
          <img :src="scope.row.imageUrl" style="width: 100%" />
        </template>
      </el-table-column> -->
      <el-table-column label="发布天数" align="center" width="100" prop="validDays"></el-table-column>
      <el-table-column label="操作" fixed="right" width="220">
        <template #default="scope">
          <!--按钮-->
          <!-- <el-button type="danger" size="small" @click="delContent(scope.row.id)">删除</el-button> -->
          <el-button type="primary" size="small" @click="showDetail(scope.row.id)" style="margin-right: 5px"
            >查看订单</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="router.push({ path: '/userPublishSellManage/publishDetail', query: { id: scope.row.id } })"
            >查看卖牛消息</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="page_style">
      <Page :total="tabData.total" :model-value="currentPage" show-elevator show-total @on-change="changePage" />
    </div>

    <el-dialog v-model="dialogTableVisible" title="报价列表" width="850">
      <el-table
        :data="tableData"
        v-loading="tableLoading"
        border
        @expand-change="checkSubOrder"
        :row-key="getRowKeys"
        :expand-row-keys="expands"
      >
        <el-table-column type="expand" label="子订单">
          <template #default="props">
            <el-table v-loading="tableLoading" :data="subOrdertableData" border>
              <el-table-column label="发运头数" prop="finalCount">
                <template #default="scope">
                  {{ scope.row.finalCount && scope.row.status != 6 ? scope.row.finalCount : scope.row.orderCount }}
                </template>
              </el-table-column>
              <el-table-column label="牛只总重" prop="finalWeight">
                <template #default="scope">
                  {{ scope.row.finalWeight && scope.row.status != 6 ? scope.row.finalWeight : scope.row.orderWeight }}
                </template>
              </el-table-column>
              <el-table-column label="总计金额(元)" prop="city">
                <template #default="scope">
                  <span style="color: #333333" v-if="scope.row.finalWeight && scope.row.status != 6">{{
                    (scope.row.finalWeight * scope.row.orderPrice).toFixed(2)
                  }}</span>
                  <span style="color: #333333" v-else>{{
                    (scope.row.orderWeight * scope.row.orderPrice).toFixed(2)
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="发运榜单" prop="address">
                <template #default="scope">
                  <img
                    style="width: 80px; height: 80px"
                    @click="
                      previewImage({
                        urlList: [
                          scope.row.updateWeightBill && scope.row.status != 6
                            ? scope.row.updateWeightBill
                            : scope.row.weightBill,
                        ],
                      })
                    "
                    :src="
                      scope.row.updateWeightBill && scope.row.status != 6
                        ? scope.row.updateWeightBill
                        : scope.row.weightBill
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="zip">
                <template #default="scope">
                  {{ subOrderStatus(scope.row.status) }}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column property="contactName" label="中标人" width="150" />
        <el-table-column property="contactPhone" label="联系方式" width="150" />
        <el-table-column property="orderPrice" label="成交价格（元/公斤）" />
        <el-table-column property="orderCount" label="成交数量（头）" />
        <el-table-column property="intendCount" label="中标时间">
          <template #default="scope">
            {{ moment(scope.row.updateTime).format('yyyy-MM-DD hh:mm:ss') || '暂无' }}
          </template>
        </el-table-column>
        <el-table-column property="status" label="状态">
          <template #default="scope">
            {{ orderStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              v-if="scope.row.buySaleContractId"
              size="small"
              @click="downloadFile(scope.row)"
              style="margin-right: 5px"
              >下载买卖合同</el-button
            >

            <el-button
              type="primary"
              v-if="scope.row.shopContract"
              size="small"
              @click="openUrl(scope.row.shopContract)"
              >下载服务合同</el-button
            >
            <el-button type="primary" v-else size="small" @click="uploadEcontract(scope.row)">上传服务合同</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="contractShow" append-to-body title="上传服务费合同" width="500">
        <el-upload
          :action="uploadUrl"
          :on-success="onSuccess"
          ref="upload"
          :headers="{ 'X-AIYANGNIU-SIGNATURE': token }"
          :on-exceed="handleExceed"
          v-model:file-list="fileList"
          :on-preview="handlePreview"
          :limit="1"
          drag
        >
          <div class="el-upload__text">将文件拖拽至此或者 <em>点击上传</em></div>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="contractShow = false">取消</el-button>
            <el-button type="primary" @click="submitFile"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { publishStatus, orderStatus, subOrderStatus } from '@/utils/system/filters'
import moment from 'moment'
import { cow, econtract } from '@/request/api'
import previewImage from '../../components/imgPreview'
import { useRouter } from 'vue-router'
import api from '@/request/apiConfig' //真实接口配置
import { ElMessage } from 'element-plus'

let dealId = ''

const router = useRouter()

const token = localStorage.aynUserToken
const uploadUrl = api.apiManager + '/manager/images/upload'
const fileList = ref([])
const upload = ref()
const shopFeeContractUrl = ref('')
const contractShow = ref(false)

const onSuccess = (res, file) => {
  console.log(res)
  fileList.value = []
  fileList.value.push(file)
  shopFeeContractUrl.value = res.data
}
const handleExceed = (files, fileList) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
  upload.value.submit()
}

const currentRow = ref({})
function uploadEcontract(row) {
  currentRow.value = row
  contractShow.value = true
}

const submitFile = () => {
  econtract
    .uploadSignedShopFeeContract({
      orderNum: currentRow.value.orderNum,
      shopContract: shopFeeContractUrl.value,
    })
    .then(res => {
      console.log(res)
      if (res.code == 101) {
        contractShow.value = false
        ElMessage({
          message: res.message || '上传成功!',
          type: 'success',
        })
        showDetail(dealId)
      } else {
        ElMessage({
          message: res.message || '上传失败!',
          type: 'warning',
        })
      }
    })
}
function downloadFile(row) {
  econtract
    .getContractDownloadUrl({ buySaleContractId: row.buySaleContractId })
    .then(res => {
      if (res.code == 101) {
        window.open(res.data)
      } else {
        ElMessage({
          message: res.message || '下载失败!',
          type: 'warning',
        })
      }
    })
    .catch(err => {
      ElMessage({
        message: err.message || '下载失败!',
        type: 'error',
      })
    })
}

function openUrl(url) {
  window.open(url)
}

let typesearchFilter = reactive({ limit: 10, offset: 0, type: 2, hasOrder: 1 })

let tabData = ref({})
const loading = ref(false)
//获取列表内容
async function getData() {
  loading.value = true
  await cow.getCattleDealPageByAdminAndType(typesearchFilter).then(res => {
    if (res.code == 101) {
      tabData.value = res || {}
    }
  })
  loading.value = false
}

let currentPage = ref(1)
//更改页码
function changePage(page) {
  if (tabData.value.limit) {
    typesearchFilter.offset = (page - 1) * tabData.value.limit //更新偏移量
    currentPage.value = page //切换当前页码
    getData() //获取广告数据
  }
}

const tableData = ref([])
let dialogTableVisible = ref(false)
let tableLoading = ref(false)
async function showDetail(id) {
  if (id) {
    dealId = id
  }
  tableLoading.value = true
  dialogTableVisible.value = true
  await cow.orderList({ dealId: id, limit: 1000 }).then(res => {
    tableData.value = res.data
  })
  tableLoading.value = false
}

const subOrdertableData = ref([])
const expands = ref([])
let getRowKeys = row => {
  //row是当前行的数据
  //给每行绑定唯一的标识
  return row.id
}

async function checkSubOrder(row, expandedRows) {
  if (expandedRows.length > 0) {
    tableLoading.value = true
    expands.value = [] //先干掉之前展开的行
    if (row) {
      expands.value.push(row.id) //push新的行 (原理有点类似防抖)
    }
    await cow.splitOrderList({ id: row.id, limit: 1000 }).then(res => {
      subOrdertableData.value = res.data
    })
    tableLoading.value = false
  } else {
    expands.value = [] //先干掉之前展开的行
  }
}

onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.contentList {
  padding: 1em;
  .page_style {
    text-align: right;
    margin-top: 1em;
    background-color: var(--system-container-background);
  }
}
</style>
