<template>
  <div class="page-container column-container">
    <!-- 搜索区 -->
    <el-form
      class="list-search-container"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      style="margin-right: 0px"
    >
	<el-form-item label="外协商：" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入外协商"
          style="width: 144px"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号：" prop="lotCode">
        <el-input
          v-model="queryParams.lotCode"
          placeholder="请输入批次号"
          style="width: 144px"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品描述：" prop="productDescription">
        <el-input
          v-model="queryParams.productDescription"
          placeholder="请输入产品描述"
          style="width: 144px"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收回日期：">
        <el-date-picker
          v-model="queryParams.startTime"
          type="date"
          style="width: 144px"
          value-format="YYYY-MM-DD"
          placeholder="选择起始日期"
          clearable
        />
        <span style="margin: 0 4px">~</span>
        <el-date-picker
          v-model="queryParams.endTime"
          type="date"
          style="width: 144px"
          value-format="YYYY-MM-DD"
          placeholder="选择结束日期"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-button
      :disabled = "dataList.find(item => item.editStatus)"
      v-if="!editStatus"
        type="primary"
        icon="Plus"
        v-hasPermi="['business:returnReceiptDetail:add']"
        @click="handleAddDetailDialog(null)"
      >
        新增
      </el-button>
      <el-button
      v-else
        type="primary"
        icon="Plus"
        v-hasPermi="['business:returnReceiptDetail:add']"
        @click="handleAddDetail(null)"
      >
        保存
      </el-button>
    </div>
    <!-- 渲染数据区 -->
    <div class="el-table-container">
      <div class="el-table-inner-container">
        <el-table
          v-loading="loading"
          :data="dataList"
          size="small"
          border
          height="100%"
          :span-method="rowSpanMethod"
        >
          <el-table-column
            label="外协商"
            align="center"
            prop="supplierName"
            width="120"
          >
          </el-table-column>
          <el-table-column
            label="批次号"
            align="center"
            prop="lotCode"
            width="120"
          />
          <el-table-column
            label="产品描述"
            align="center"
            prop="productDescription"
          />
          <el-table-column
            label="收回日期"
            align="center"
            prop="formDate"
            width="100"
          >
            <template #default="scope">
              {{ parseTime(scope.row.formDate, "{y}-{m}-{d}") }}
            </template>
          </el-table-column>
          <el-table-column label="外协数量" align="center" prop="productNum" width="90"/>
          <el-table-column
            label="外协工序"
            align="center"
            prop="processAlias"
            width="120"
          ></el-table-column>
          <el-table-column
            label="原箱号"
            align="center"
            prop="originalCarrier"
            width="120"
          />
          <el-table-column
            label="新箱号"
            align="center"
            prop="newCarrier"
            width="120"
          />
          <el-table-column label="备注" align="center" prop="remark">
            <template #default="scope">
              <el-input
                v-model="scope.row.remark"
                v-if="!scope.row.editAuditStatus &&scope.row.editStatus"
              />
              <span v-else>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="isAudit" width="80">
            <template #default="scope">
              <dict-tag
                :options="is_audit_num"
                :value="scope.row.isAudit"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="收回数量"
            align="center"
            prop="receiptNum"
          ></el-table-column>
          <el-table-column
            label="确定数量"
            align="center"
            prop="auditNum"
            width="150"
          >
            <template #default="scope">
              <el-input-number
                v-if="scope.row.editStatus || scope.row.editAuditStatus"
                v-model="scope.row.auditNum"
                :min="0"
                controls-position="right"
                style="text-align: center"
              />
              <span v-else>{{ scope.row.auditNum }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="250"
          >
		  <template #default="scope">
			<!-- 保存按钮 -->
			<el-button
				v-if="scope.row.productionDeptId == 0 && scope.row.editStatus == true"
				link
        :disabled = "scope.row.allowClick == false"
				:loading="isSubmitting"
        v-hasPermi="['business:returnReceiptDetail:add']"
				type="primary"
				icon="Check"
				@click="handleAdd(scope.row)"
			>保存</el-button>

			<!-- 编辑按钮 -->
			<el-button
				v-if="scope.row.productionDeptId == 0 && scope.row.editStatus == false "
				link
        :disabled = "scope.row.allowClick == false"
				type="warning"
        v-hasPermi="['business:returnReceiptDetail:edit']"
				icon="Edit"
				@click="handleEditAuditNum(scope.row)"
			>编辑</el-button>

			<!-- 审核通过按钮 -->
			<el-button
				v-if="scope.row.status === 0 &&scope.row.isAudit ==1 && scope.row.id && scope.row.editStatus == false && scope.row.editAuditStatus == false"
				link
        :disabled = "scope.row.allowClick == false"
				type="warning"
        v-hasPermi="['business:returnReceiptDetail:edit']"
				icon="CircleCheck"
				@click="handleCheckDetail(scope.row)"
			>审核通过</el-button>

			<!-- 审核不通过按钮 -->
			<el-button
				v-if="scope.row.status === 1 &&scope.row.isAudit ==1 && scope.row.id && scope.row.editStatus == false && scope.row.editAuditStatus == false"
				link
        :disabled = "scope.row.allowClick == false"
				type="warning"
        v-hasPermi="['business:returnReceiptDetail:edit']"
				icon="CircleClose"
				@click="handleNotCheckDetail(scope.row)"
			>审核不通过</el-button>

			<!-- 反选按钮 -->
			<el-button
				v-if="scope.row.id && scope.row.productionDeptId == 0 && scope.row.editStatus == false"
				link
        :disabled = "scope.row.allowClick == false"
        v-hasPermi="['business:returnReceiptDetail:remove']"
				type="danger"
				icon="Delete"
				@click="handleDelReturnReceiveDetail(scope.row)"
			>反选</el-button>
			</template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 表单 -->
    <receipt-detail-form ref="receiptDetailRef" @handleSaveSuccess="getList" />
    <!-- 收回明细选择 -->
    <dialog-outsource-details
      ref="dialogOutsourceDetailsRef"
      :multiple-selected="handleMultipleSelectedOutsourceDetails"
    />
  </div>
</template>

<script setup name="returnReceiptDetail">
import { listDetail,saveDetails,delReceiptDetail,saveDetailsForAdd} from '@/api/business/returnReceiptDetail'
import receiptDetailForm from './form'
import dialogOutsourceDetails from './DialogOutsourceDetails'
const { proxy } = getCurrentInstance()
/** 字典数组区 */
const { is_audit_num } = proxy.useDict("is_audit_num");

const spanProps = ref([])
const dataList = ref([])
const loading = ref(true)
const editStatus = ref(false)
const detailList = ref([])
const isSubmitting = ref(false)
const ids = ref([])
const total = ref(0)
/** 查询对象 */
const queryParams = ref({
	pageNum: 1,
	pageSize: 10,
	formCode: null,
	formDate: null,
	startTime:null,
	endTime:null,
    supplierName:null
})

/***********************  方法区  ****************************/

/** 查询外协单主
带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子列表 */
function getList() {
	loading.value = true
  editStatus.value = false
	listDetail(queryParams.value).then((response) => {
		dataList.value = response.rows
		dataList.value.forEach(item => {
			item.editStatus = false
			item.editAuditStatus = false
      item.allowClick = true
		})
		total.value = response.total
		loading.value = false
		spanProps.value = ['lotCode','productDescription','productNum','originalCarrier','newCarrier'];
		spanPropGroup(dataList.value)
	})
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1
	getList()
}

/** 重置按钮操作 */
function resetQuery() {
	queryParams.value= ref({
	pageNum: 1,
	pageSize: 10,
	formCode: null,
	formDate: null,
	startTime:null,
	endTime:null
})
	handleQuery()
}
/**复选框选中数据 */
function handleSelectionChange(selection) {
	ids.value = selection.map((item) => item.id)
}
// 外协明细选择带回
const handleMultipleSelectedOutsourceDetails = (selection) => {
	console.log(selection)
  dataList.value.forEach(item=>{
    item.allowClick = false
  })
  editStatus.value = true
	for(let i = 0;i<selection.length;i++) {
		for(let j = 0;j<selection[i].processes.length;j++) {
			const newDetail = {
			outsourceDetailId: selection[i].id,
			productDescription: selection[i].productDescription,
			lotCode:selection[i].lotCode,
			lotId:selection[i].lotId,
			dayworkId:selection[i].dayworkId,
			productId:selection[i].productId,
			productNum: selection[i].productNum,
			receiptNum: selection[i].processes[j].qualifiedNum?selection[i].processes[j].qualifiedNum:0,
			originalCarrier:selection[i].originalCarrier,
			originalCarrierCount:selection[i].originalCarrierCount,
			newCarrier:selection[i].newCarrier,
			newCarrierCount:selection[i].newCarrierCount,
			processNames: selection[i].processNames,
			formDate:proxy.parseTime(new Date(), '{y}-{m}-{d}'),
			remark: '',
			supplierName:selection[i].supplierName,
			supplierId:selection[i].supplierId,
			technologicalProcessId:selection[i].processes[j].technologicalProcessId,
			technologyVersion:selection[i].processes[j].technologyVersion,
			technologicalProcessDetailId:selection[i].processes[j].technologicalProcessDetailId,
			processId:selection[i].processes[j].processId,
			processAlias:selection[i].processes[j].processAlias,
			processCode:selection[i].processes[j].processCode,
			processStepNumber:selection[i].processes[j].processStepNumber,
			status:0,
			auditNum:selection[i].processes[j].qualifiedNum?selection[i].processes[j].qualifiedNum:0,
			editStatus:true,
      isAudit:0
			}
		    dataList.value.unshift(newDetail)
        //存放新增的明细，走总的保存方法
        detailList.value.push(newDetail)
			spanPropGroup(dataList.value)
		}
		}
}
//新增明细
function handleAdd(row) {
	var flag = true;
	if(isSubmitting.value) {
		return
	}
	isSubmitting.value = true	
	let tempList = dataList.value.filter(item=>{
	return item.outsourceDetailId == row.outsourceDetailId})
  //保存时将确认状态置为1，从而让状态变成已确认
	for(let i = 0;i<tempList.length;i++) {
		if(tempList[i].auditNum == 0){
			isSubmitting.value = false
			proxy.$modal
      .confirm("第" + (i + 1) + "道序确定数量是否确定为0")
      .then(() => {
      })
      .catch(() => {
        flag = false; 
        isSubmitting.value = false; 
      })
	  .finally(() => {
		console.log(flag)
        // 无论用户点击确定还是取消，都在这里检查 flag 值
        if (flag) {
          saveDetails(tempList).then(res => {
            proxy.$modal.msgSuccess('操作成功');
            isSubmitting.value = false;
            getList();
          });
        }
      });
    return;
  }
}
if(flag) {
	saveDetails(tempList).then(res => {
            proxy.$modal.msgSuccess('操作成功');
            isSubmitting.value = false;
            getList();
          });
}
}
//总保存方法
function handleAddDetail() {
  var flag = true;
  for(let i = 0;i<detailList.value.length;i++) {
		if(detailList.value[i].auditNum == 0){
			proxy.$modal
      .confirm("第" + (i + 1) + "行确定数量是否确定为0")
      .then(() => {
      })
      .catch(() => {
        flag = false; 
      })
	  .finally(() => {
      console.log(flag)
        // 无论用户点击确定还是取消，都在这里检查 flag 值
        if (flag) {
          saveDetailsForAdd(detailList.value).then(res => {
            editStatus.value = false
            proxy.$modal.msgSuccess('操作成功');
            getList();
          });
        }
      });
    return;
  }
}
if(flag) {
  saveDetailsForAdd(detailList.value).then(res => {
            editStatus.value = false
            proxy.$modal.msgSuccess('操作成功');
            getList();
          });
}
}
//审核通过
function handleCheckDetail(row) {
	let tempList = dataList.value.filter(item=>{
	return item.outsourceDetailId == row.outsourceDetailId})
  console.log(tempList)
	tempList.forEach(item=>{
		item.status = 1
	})
	saveDetails(tempList).then(res=>{
			proxy.$modal.msgSuccess('操作成功')
				getList()
		})
}
//审核不通过
function handleNotCheckDetail(row) {
	let tempList = dataList.value.filter(item=>{
	return item.outsourceDetailId == row.outsourceDetailId})
	tempList.forEach(item=>{
		item.status = 0
	})
	saveDetails(tempList).then(res=>{
			proxy.$modal.msgSuccess('操作成功')
				getList()
		})
}
//编辑
function handleEditAuditNum(row) {
	let tempList = dataList.value.filter(item=>{
	return item.outsourceDetailId == row.outsourceDetailId})
	tempList.forEach(item=>{
		item.editAuditStatus = true
		item.editStatus = true
	})
  //除了选中的数据
  let infoList = dataList.value.filter(item=>{
	return item.outsourceDetailId != row.outsourceDetailId})
  infoList.forEach(item=>{
		item.allowClick = false
	})
  console.log(row)
}
//反选操作
function handleDelReturnReceiveDetail(row) {
	proxy.$modal
    .confirm("是否确认删除选中的数据项,如果删除，同时删除该批次下所有工序？")
    .then(function () {
		delReceiptDetail(row.outsourceDetailId).then(res=>{
			proxy.$modal.msgSuccess('操作成功')
				getList()
		})
    })
}
//新增明细
function handleAddDetailDialog() {
	var info = {} 
	info.outsourceDetailIds = dataList.value.length>0?dataList.value.map((item) => item.outsourceDetailId):[]
	proxy.$refs.dialogOutsourceDetailsRef.open(info)
}
/** 修改按钮操作 */
function handleShowFormDialog(row) {
	if (row) {
    row.editStatus = false;
  }
  proxy.$refs.receiptDetailRef.open(row ? row : null);
}
let rowSpansMap = new Map(); //存需要开始合并的行号，向下合并多少行

const spanPropGroup = (data) => {
  let oldRow = null; //需要合并的行
  rowSpansMap = new Map(); //重置Map
  oldRow = data[0]; //默认第0行为需要合并的行
  rowSpansMap.set(0, 1); //第0行，向下合并一行(其实就是自己单独一行)
  let spanRow = 0; //记录需要开始合并的行号
  for (let i = 1; i < data.length; i++) {
    const item = data[i];
    let isSame = true;
    //遍历需要判断的属性判断对应值是否全部相等
    for (let j = 0; j < spanProps.value.length; j++) {
      const prop = spanProps.value[j];
      //只要有一个属性值不相等则记录新的需要合并的行号
      if (item[prop] != oldRow[prop]) {
        oldRow = item;
        rowSpansMap.set(i, 1);
        spanRow = i;
        isSame = false;
        break;
      }
    }
    //如果所有属性值相同则所需要合并的行数+1
    if (isSame) {
      let span = rowSpansMap.get(spanRow);
      rowSpansMap.set(spanRow, span + 1);
    }
  }
};
 
const rowSpanMethod =({ row, column, rowIndex, columnIndex }) => {
  //采样值5-9列所对应的行不需要合并
  if (columnIndex != 10&&columnIndex != 8&&columnIndex != 5&&columnIndex != 11) {
    //根据当前行号从map中获取开始合并的行根据当前行号从map中获取开始合并的行号，向下合并多少行
    const span = rowSpansMap.get(rowIndex);
    if (span != null) {
      return {
        rowspan: span, //向下合并span行
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
/** 导出按钮操作 */
function handleExport() {
	proxy.download(
		'business/returnReceipt/export',
		{
			...queryParams.value
		},
		`order_${new Date().getTime()}.xlsx`
	)
}
getList()
</script>
