<template>
  <el-card class="hl-card">
    <template #header>
      <span>订单信息</span>
    </template>
    <ContentWrap class="borderxx">
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="108px">
        <el-form-item label="项目编号" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" class="!w-240px" />
        </el-form-item>

        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" class="!w-240px" />
        </el-form-item>
        <el-form-item label="业务员" prop="businessManName">
          <el-input v-model="queryParams.businessManName" placeholder="请输入业务员" clearable @keyup.enter="handleQuery" class="!w-240px" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" class="!w-240px" />
        </el-form-item>
        <el-form-item label="是否有价格" prop="hasPrice">
          <el-select v-model="queryParams.hasPrice" placeholder="请选择是否有价格" clearable class="!w-240px">
            <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否已变更" prop="hasAlter">
          <el-select v-model="queryParams.hasAlter" placeholder="请选择是否已变更" clearable class="!w-240px">
            <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="单据状态" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择单据状态" clearable class="!w-240px">
            <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_ORDER_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="发货状态" prop="deliveryStatus">
          <el-select v-model="queryParams.deliveryStatus" placeholder="请选择发货状态" clearable class="!w-240px">
            <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_DELIVERY_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" type="primary">
            <Icon icon="ep:search" class="mr-5px" /> 搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> 重置
          </el-button>
          <el-button type="primary" plain @click="openDetail('create')" v-hasPermi="['heli:project-order:create']">
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['heli:project-order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table
ref="multipleTableRef"
                @selection-change="handleSelectionChange"
                v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" class="hl-table">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="100" fixed label="序号" align="center" />
        <el-table-column fixed label="项目编号" align="center" prop="code" width="240">
          <template #default="scope">
            <el-button type="text" @click="openDetail('detail', scope.row.id)">{{
              scope.row.code
            }}</el-button></template>
        </el-table-column>
        <el-table-column fixed label="订单日期" align="center" prop="orderTime" :formatter="dateFormatter2" width="180" />
        <!-- <el-table-column label="提出部门" align="center" prop="businessDeptName" width="150" /> -->
        <!-- <el-table-column label="业务员" align="center" prop="businessManName" width="150" /> -->
        <el-table-column label="客户名称" align="center" prop="customerName" width="240" />
        <el-table-column label="合同编号" align="center" prop="contractNo" width="180" />
        <el-table-column label="项目名称" align="center" prop="projectName" width="180" />
        <!-- <el-table-column label="所属业务线" align="center" prop="businessLine" width="150">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_BUSINESS_LINE" :value="scope.row.businessLine" />
          </template>
        </el-table-column> -->
        <el-table-column label="是否有价格" align="center" prop="hasPrice" width="150">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_COMMON_IS_OR_NOT" :value="scope.row.hasPrice" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="价格（元）" align="center" prop="price" width="150" /> -->
        <!-- <el-table-column label="币种" align="center" prop="currency" width="150">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_CURRENCY" :value="scope.row.currency" />
          </template>
        </el-table-column> -->
        <el-table-column label="是否紧急" align="center" prop="isUrgency" width="150">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_COMMON_IS_OR_NOT" :value="scope.row.isUrgency" />
          </template>
        </el-table-column>
        <el-table-column label="性质" align="center" prop="property" width="120">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_PROJECT_PROPERTY" :value="scope.row.property" />
          </template>
        </el-table-column>
        <el-table-column label="起止日期" align="center" prop="projectStartTime" width="260">
          <template #default="scope">
            {{
              formatDate(scope.row.projectStartTime, 'YYYY-MM-DD') +
              '~' +
              formatDate(scope.row.projectEndTime, 'YYYY-MM-DD')
            }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="是否已变更" align="center" prop="hasAlter" width="150">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_COMMON_IS_OR_NOT" :value="scope.row.hasAlter" />
          </template>
        </el-table-column>
        -->
        <el-table-column label="单据状态" align="center" prop="orderStatus" fixed="right" width="120">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_PROJECT_ORDER_STATUS" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <el-table-column label="发货状态" align="center" prop="deliveryStatus" fixed="right" width="120">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_DELIVERY_STATUS" :value="scope.row.deliveryStatus" />
          </template>
        </el-table-column>
        <el-table-column align="right" fixed="right" min-width="200">
          <template #header> <span style="margin-right: 30%">操作</span> </template>
          <template #default="scope">
            <el-row>
              <el-col>
                <el-button link type="danger" @click="handleDelete(scope.row.id)" v-if="(scope.row.orderStatus == 4 && scope.row.hasAlter == 0) ||scope.row.orderStatus == 3 ">
                  删除
                </el-button>
<!--                <el-button link type="primary"  @click="openDetail('price',scope.row.id)" v-if="scope.row.orderStatus!=4&&scope.row.hasPrice==1">-->
<!--                   录入价格-->
<!--                </el-button>-->
                <el-button link type="primary" @click="openDetail('update', scope.row.id)" v-if="scope.row.orderStatus == 4 || scope.row.orderStatus == 3">
                  编辑
                </el-button>
                <el-dropdown @command="(command) => handleCommand(command, scope.row.id,scope.row.property, scope.row.code)">
                  <span class="el-dropdown-link">更多
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="detail">查看详情</el-dropdown-item>
                      <el-dropdown-item v-if="scope.row.orderStatus == 32" command="printProject">
                        打印开发项目启动单
                      </el-dropdown-item>

                      <el-dropdown-item v-if="scope.row.orderStatus == 32 && scope.row.deliveryStatus != 3" command="alter">订单变更</el-dropdown-item>
                      <el-dropdown-item command="viewArchive">查看归档日志</el-dropdown-item>
                      <el-dropdown-item v-if="scope.row.orderStatus == 32 && scope.row.deliveryStatus != 3" command="delivery">去发货</el-dropdown-item>
                      <el-dropdown-item v-if="scope.row.deliveryStatus == 3" command="trialReport">试模报告</el-dropdown-item>
                      <el-dropdown-item v-if="scope.row.deliveryStatus == 3" command="confirmReport">认可报告</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </ContentWrap>
  </el-card>
  <!-- 【打印启动单】 - 弹框-->
  <Print ref="printRef" />

  <ReportDialog
ref="reportRef"
                :key="dialogKey"
                :type="reportBusinessType"
                :file-type="reportBusinessFileType"
                :id="reportBusinessId"
                :title="reportBusinessTitle" />
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, dateFormatter2, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import * as ProjectOrderApi from '@/api/heli/projectorder'
import Print from './startprint.vue' // 引入打印弹框
import { ref } from 'vue'
import {useCommonStore} from "@/store/modules/common";
import {ElTable} from "element-plus";
import {ProjectOrderVO} from "@/api/heli/projectorder";

defineOptions({ name: 'ProjectOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const commonStore = useCommonStore()

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  orderStatus: undefined,
  deliveryStatus: undefined,
  businessDeptId: undefined,
  customerName: undefined,
  projectName: undefined,
  businessLine: undefined,
  blueprintNo: undefined,
  hasPrice: undefined,
  price: undefined,
  currency: undefined,
  projectStartTime: [],
  projectEndTime: [],
  isUrgency: undefined,
  property: undefined,
  referenceTechnology: undefined,
  hasAlter: undefined,
  lastAlterTime: [],
  qualityRequirement: undefined,
  remark: undefined,
  hasContract: undefined,
  hasTechnologyProtocol: undefined,
  hasBlueprint: undefined,
  blueprintRemark: undefined,
  status: undefined,
  createTime: [],
  businessManName: undefined,
  isSnapshot: 0,
  snapshotId: undefined,
  snapshotCode: undefined,
  orderTime: [],
  snapshotOrderTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const reportRef = ref()
const reportBusinessType = ref('PROJECT_ORDER_REPORT')
const reportBusinessFileType = ref('')
const reportBusinessId = ref()
const reportBusinessTitle = ref('')
const reportKey = ref(0)
const dialogKey = ref(0)

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<ProjectOrderVO[]>([])
const handleSelectionChange = (val: ProjectOrderVO[]) => {
  multipleSelection.value = val
}

const openReport = () => {
  reportRef.value.open()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
	  debugger
	  const route = useRoute();

	  if(route){
		  const idid = route.query.idid;
		  queryParams.code=idid
	  }

    const data = await ProjectOrderApi.getProjectOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openDetail = (type: string, id?: number) => {
  router.push({
    name: 'ProjectOrderDetail',
    query: {
      active: type,
      id: id
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProjectOrderApi.deleteProjectOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    if(!multipleSelection.value || multipleSelection.value.length == 0){
      message.warning(t('common.selectText'))
      return
    }
    let idList = [];
    multipleSelection.value.forEach(p => {
      idList.push(p.id)
    })
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProjectOrderApi.exportProjectOrder({"idList": idList})
    download.excel(data, '项目订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleCommand = async (command, id,property, code) => {
  switch (command) {
    case 'detail':
      openDetail('detail', id)
      break
    case 'printProject':
      printHandle(id,property)
      break
    case 'alter':
      openDetail('alter', id)
      break
    case 'viewArchive':
      router.push({
        name: 'ProjectOrderArchive',
        query: {
          code: code
        }
      })
      break
    case 'delivery':
      router.push({
        name: 'DeliverOrderDetail',
        query: {
          active: 'deliver',
          projectOrderId: id,
          operateId: Math.random()
        }
      })
      break
    case 'trialReport':
      reportKey.value++
      reportBusinessFileType.value = 'TRIAL_REPORT'
      reportBusinessId.value = id
      reportBusinessTitle.value = '试模报告'
      openReport()
      break
    case 'confirmReport':
      reportKey.value++
      reportBusinessFileType.value = 'CONFIRM_REPORT'
      reportBusinessId.value = id
      reportBusinessTitle.value = '认可报告'
      openReport()
      break
  }
}

// 打印启动单
const printRef = ref() // 打印弹框
const dialogInfo = ref({}) // 打印弹框数据
// 打印启动单
const printHandle = (id,property) => {
  printRef.value.open(id,property)
}

/** 初始化 **/
onMounted(() => {
  getList()
})
onActivated(() => {
  getList()
})
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  margin: 5px;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
