<template>
  <view class="page-wraper">
    <view class="page-header">
      <view class="header-view">
        <view class="header_job_top">
          <job-top :dataContent="jobContent"></job-top>
        </view>
        <view class="cen_card" style="padding: 5rpx;">
          <view class="cell_box uni-flex uni-row">
            <view class="cell_info">
              <view class="text_lightblue">发货类型</view>
              <view>{{ jobContent.deliverType }}</view>
            </view>

            <view class="cell_info">
              <view class="text_lightblue">客户代码</view>
              <view>{{ jobContent.customerCode }}</view>
            </view>

            <view class="cell_info">
              <view class="text_lightblue">目标库位</view>
              <view>{{ toLocationCode }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="page-main">
      <scroll-view scroll-y="true" class="page-main-scroll">
        <view>
          <comDeliverDetailCardBatch ref='comIssueDetailCard' :dataContent="detailSource" :settingParam="jobContent"
                                     @updateData='updateData'>
          </comDeliverDetailCardBatch>
        </view>
      </scroll-view>
    </view>

    <view class="page-footer">
      <view class="uni-flex u-col-center space-between padding_10" style="background-color:ghostwhite; width: 100%; ">
        <view class="">
        </view>
        <view class=" uni-flex uni-row">
          <button class="btn_single_commit" hover-class="btn_commit_after" @click="submit()">提交</button>
        </view>
      </view>
    </view>

    <win-scan-button @goScan='openScanDetailPopup'></win-scan-button>
    <comScanDeliverPackBatch ref="comScanIssuePack" @closeScan='closeScan' @updateData='updateData'>
    </comScanDeliverPackBatch>
    <comMessage ref="comMessage"></comMessage>
  </view>
</template>

<script setup lang="ts">
import {
  getDeliverDetail,
  takeDeliverJob,
  cancleTakeDeliverJob,
  deliverJobSubmit
} from '@/api/request2.js';


import {
  calc
} from '@/common/calc.js';

import {
  goHome,
  navigateBack,
  getRemoveOption,
  getCurrDateTime,
  getPackingNumberAndBatch,
  deepCopyData
} from '@/common/basic.js';

import {
  getDataSource
} from '@/pages/issue/js/issue.js';

import {
  getManagementPrecisions
} from '@/common/balance.js';


import jobDetailPopup from '@/mycomponents/job/jobDetailPopup.vue'
import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import comDeliverDetailCardBatch from '@/pages/deliver/coms/comDeliverDetailCardBatch.vue'
import comScanDeliverPackBatch from '@/pages/deliver/coms/comScanDeliverPackBatch.vue'
import jobTop from '@/mycomponents/job/jobTop.vue'


import {ref} from 'vue';
import {onLoad, onNavigationBarButtonTap, onBackPress} from '@dcloudio/uni-app';

const id = ref('');
const jobContent = ref({});
const subList = ref([]);
const detailSource = ref([]);
const detailOptions = ref([]);
const scanOptions = ref([]);
const status = ref("");
const toLocationCode = ref("");
const jobStatus = ref("");
const dataContent = ref('')

const managementList = ref([]);
const comMessage = ref(null);
const scanPopup = ref(null);
const comScanIssuePack = ref(null);
import {useCountStore} from '@/store'
const store = useCountStore();

onLoad((option) => {
  uni.setNavigationBarTitle({
    title: option.title + '详情'
  });
  id.value = option.id;
  if (id.value != undefined) {
    // 新建的任务自动接收
    if (option.status == "1") {
      receive(() => {
        getDetail();
      });
    } else {
      getDetail();
    }
  }
});

onNavigationBarButtonTap((e) => {
  if (e.index === 0) {
    goHome();
  }
});

onBackPress((e) => {
  // 已经接收但是没提交任务
  if (e.from == 'backbutton') {
    if (jobStatus.value == "2") {
      // 取消承接任务
      cancleTakeDeliverJob(id.value).then(() => {
        uni.navigateBack();
      }).catch(() => {
        uni.navigateBack();
      });
    } else {
      uni.navigateBack();
    }
    return true;
  }
});

const receive = (callback) => {
  if (id.value != null) {
    takeDeliverJob(id.value).then(() => {
      callback();
    }).catch((error) => {
      showErrorMessage(error);
    });
  }
};

const getDetail = () => {
  uni.showLoading({
    title: "加载中....",
    mask: true
  });
  getDeliverDetail(id.value).then((res) => {
    uni.hideLoading();
    if (res.data && res.data.subList.length > 0) {
      jobContent.value = res.data;
      jobStatus.value = res.data.status;
      subList.value = res.data.subList;
      detailSource.value = res.data;
      toLocationCode.value = subList.value[0].toLocationCode;
      resizeCollapse();
    } else {
      showMessage('未获取到详情');
    }
  }).catch((error) => {
    uni.hideLoading();
    showErrorMessage(error);
  });
};

const closeScan = () => {
  resizeCollapse();
};

const resizeCollapse = () => {
  // 实现具体逻辑
};

const submit = () => {
  uni.showLoading({
    title: "提交中....",
    mask: true
  });

  // 目前任务只到一个库位
  const itemCodes = [];
  const locationCode = detailSource.value.subList[0].toLocationCode;
  detailSource.value.subList.forEach((item) => {
    itemCodes.push(item.itemCode);
  });

  // 获取管理模式，封装参数
  getManagementPrecisions(itemCodes, locationCode, (res) => {
    if (res.success) {
      managementList.value = res.list;
      submitJob();
    } else {
      uni.hideLoading();
      showErrorMessage(res.message);
    }
  });
};

const checkCount = () => {
  let str = "";
  let taskQty = 0;
  let totalQty = 0;
  detailSource.value.subList.forEach((item) => {
    taskQty = calc.add(taskQty, item.qty);
    const handleQty = item.qty ? item.qty : 0;
    totalQty = calc.add(totalQty, handleQty);
    // 实际扫描的数量
    item.totalQty = totalQty;
  });

  // 如果允许部分提交任务有扫描记录就可以直接提交；如果不允许部分执行，任务数量和提交数量不一致给出提示
  if (jobContent.value.allowPartialComplete == "FALSE") {
    detailSource.value.subList.forEach((detail) => {
      if (taskQty != totalQty) {
        str += `物料号【${detail.itemCode}】任务数量【${taskQty}】与实际提交数量【${totalQty}】不一致\n`;
      }
    });
  }

  if (str) {
    str = '不允许提交\n' + str;
    showErrorMessage(str);
  }

  return str ? false : true;
};

const submitJob = () => {
  const params = setParams();
  console.log("提交参数", params);
  if (params.subList.length == 0) {
    uni.hideLoading();
    comMessage.value.showConfirmMessageModal('请扫描箱码');
    return;
  }

  if (!checkCount()) {
    uni.hideLoading();
    return;
  }

  deliverJobSubmit(params).then((res) => {
    uni.hideLoading();
    if (res.data) {
      showCommitSuccessMessage("提交成功\n生成发货记录\n" + res.data);
    } else {
      showErrorMessage("提交失败[" + res.msg + "]");
    }
  }).catch((error) => {
    uni.hideLoading();
    showErrorMessage(error);
  });
};

const setParams = () => {
  const subList = [];
  const createTime = getCurrDateTime();
  const creator = store.id;

  detailSource.value.subList.forEach((r) => {
    if (r.scaned) {
      const subItem = {...r};
      subItem.recordList = [];
      const record = {};
      record.handleQty = r.handleQty;
      record.toContainerNumber = r.ContainerNumber;
      record.toInventoryStatus = r.inventoryStatus;
      record.toLocationCode = subItem.toLocationCode;
      record.supplierCode = r.supplierCode;
      const info = getPackingNumberAndBatch(managementList.value, r.itemCode, r.packingNumber, r.batch);
      record.toPackingNumber = info.packingNumber;
      record.packingNumber = info.packingNumber;
      record.fromPackingNumber = info.packingNumber;
      record.toBatch = info.batch;
      subItem.toPackingNumber = info.packingNumber;
      subItem.packingNumber = info.packingNumber;
      subItem.fromPackingNumber = info.packingNumber;
      subItem.recordList.push(record);
      subList.push(deepCopyData(subItem));
    }
  });

  jobContent.value.subList = subList;
  jobContent.value.createTime = createTime;
  jobContent.value.creator = creator;
  return jobContent.value;
};

const cancel = () => {
  comMessage.value.showQuestionMessage('是否要清空已扫描的物料和目标库位信息?', (res) => {
    if (res) {
      clearInfo();
    }
  });
};

const clearInfo = () => {
  dataContent.value.itemCodeList.forEach((res) => {
    if (res.recommendList != null) {
      res.recommendList.forEach((res1) => {
        if (res1.locationCodeList != null) {
          res1.locationCodeList.forEach((res2) => {
            if (res2.packingCodeList != null) {
              res2.packingCodeList.forEach((res3) => {
                res3.itemCode = "";
                res3.qty = 0;
              });
            }
          });
        }
      });
    }
  });
};

const updateData = (record) => {
};

const scanPopupGetFocus = () => {
  if (scanPopup.value != undefined) {
    scanPopup.value.getfocus();
  }
};

const showMessage = (message) => {
  comMessage.value.showMessage(message, (res) => {
    if (res) {
      afterCloseMessage();
    }
  });
};

const showErrorMessage = (message) => {
  comMessage.value.showErrorMessage(message, (res) => {
    if (res) {
      afterCloseMessage();
    }
  });
};

const showScanMessage = (message) => {
  comMessage.value.showScanMessage(message);
};

const showCommitSuccess = () => {
  comMessage.value.showCommitSuccess();
};

const showCommitSuccessMessage = (hint) => {
  comMessage.value.showSuccessMessage(hint, (res) => {
    navigateBack(1);
  });
};

const showRescanMessage = (message) => {
  comMessage.value.showRescanMessage(message);
};

const afterCloseMessage = () => {
  scanPopupGetFocus();
};

const closeScanMessage = () => {
  scanPopupGetFocus();
};

const confirm = (data) => {
  dataContent.value = data;
};

const confirmResult = (result) => {
  dataContent.value = result;
};

const openScanDetailPopup = () => {
  const datacontent = {...detailSource.value}; // 深度克隆
  comScanIssuePack.value.openScanPopup(datacontent, jobContent.value);
};

const closeScanPopup = () => {
  // updateCommitBtn();
};

</script>

<style scoped lang="scss">
.uni-numbox__value {
  width: 40px;
}

button[disabled] {
  background-color: #3C9CFF;
  color: #fff;
  opacity: 0.7;
}


// /deep/ .input-value {
// 	font-size: 16px;
// }

// /deep/ .uni-collapse-item__title-text {
// 	font-size: 16px;
// }

// /deep/ .uni-collapse-item--border {
// 	border-bottom-width: 0px;
// 	border-bottom-color: #ebeef5;
// }

// /deep/ .uni-collapse-item--border {
// 	border-bottom-width: 1px;
// 	border-bottom-color: #ebeef5;
// }
</style>