<template>
  <view class="page-product-receipt">

    <page-head title="白坯检验" />

    <u-form id="form" class="page-form" ref="form" label-width="180rpx">
      <u-form-item required  label="日期">
        <u-input @click="showCalendar = true" placeholder="请选择日期" v-model="form.checkDate" :clearable="true"  readonly />
        <u-icon name="close-circle-fill" @click="clearDate" color="rgb(96, 98, 102)" size="28"></u-icon>
      </u-form-item>
      <u-form-item required  label="物料清单">
        <u-input @click="clickShowList" v-model="form.materialName" placeholder="请选择物料清单" :show-action="false"  readonly ></u-input>
        <u-icon name="close-circle-fill" @click="clearMaterial" color="rgb(96, 98, 102)" size="28"></u-icon>
      </u-form-item>

      <u-form-item label="来料批号">
        <u-input placeholder="请输入来料批号" v-model="form.incomeBatchNo" :show-action="false"></u-input>
      </u-form-item>

      <u-form-item required  label="检查数量">
        <u-input placeholder="请输入检查数量（PC）" v-model="form.checkNum" :show-action="false"></u-input>
      </u-form-item>

      <u-form-item required  label="是否合格">
        <jPicker sureColor="#ff0000" moren="请选择是否合格" @bindpicker="selectIsQualified" showKey="key" valKey="value" :val="form.isQualified" :options="optionResults" />
      </u-form-item>

      <u-form-item label="不良数量（车）"  label-width="230rpx">
        <span style="width: 100%;color: #c0c4cc" @click="checkShowDefects" v-if="!form.badNum">请选择不良项</span>
        <span v-if="form.badNum">{{form.badNum}}</span>
      </u-form-item>

      <u-form-item label="不良选项">
        <span style="width: 100%;color: #c0c4cc"  @click="checkShowDefects" v-if="defectList.length === 0">请选择不良项</span>
        <span style="width: 100%;color: #2979ff"  @click="checkShowDefects" v-if="defectList.length > 0">点击查看</span>
      </u-form-item>

      <u-form-item label="不合格原因">
        <u-input placeholder="请填写不合格原因" v-model="form.remark" :show-action="false"></u-input>
      </u-form-item>

    </u-form>



    <view class="bottom-bar">
      <u-button type="primary" @click="submit" >提交</u-button>
    </view>

    <u-calendar v-model="showCalendar" :mode="'date'" @change="changeDate" :max-date="maxDate"></u-calendar>

    <u-popup id="popup" v-model="showList" mode="center" width="90%" height="60%">
      <scroll-view id="list" scroll-y="true" :style="{ height: listHeight + 'px' }" :lower-threshold="50">
        <u-form class="list">
          <view v-if="list.length > 0">
            <view class="list-item" v-for="(item, index) in list" :key="index" @click="clickItem(index)" >
              <lj-list-row label="物料编号:" :value="item.materialCode" />
              <lj-list-row label="白坯名称:" :value="item.materialName" />
            </view>
          </view>
          <view v-else> 暂无数据 </view>
        </u-form>
      </scroll-view>

    </u-popup>

    <u-popup
      id="popup-content"
      v-model="showDefects"
      mode="center"
      :mask-close-able="false"
      width="600rpx"
      height="60%"
      borderRadius="12rpx"
    >
      <view class="popup-content" >

        <!-- 表格容器（带滚动） -->
        <scroll-view
          class="table-scroll"
          scroll-y
          :style="{height: `${tableHeight}rpx`}"
        >
          <view class="table" id="table">
            <!-- 表头 -->
            <view class="table-header">
              <view class="table-th" style="  flex: 1;">数量</view>
              <view class="table-th" style="  flex: 3;">缺陷类型</view>
              <view class="table-th" style="  flex: 1;">操作</view>
            </view>

            <!-- 表格内容行 -->
            <view class="table-body">
              <view class="table-tr" v-for="(item, index) in defectList" :key="index">
                <view class="table-td" style="  flex: 1;">
                  <u-input
                    v-model.number="item.quantity"
                    type="number"
                    placeholder="数量"
                    min="1"
                  />
                </view>
                <view class="table-td" style="  flex: 3;" @click="clickDefectsIndex(index)">
                  <jPicker sureColor="#ff0000" moren="请选择不良项" @bindpicker="selectBadItem"  showKey="className" valKey="id" :val="item.badItem" :options="optionDefects" />
                </view>
                <view class="table-td" style="  flex: 1;">
                  <u-icon
                    name="close"
                    color="#ff4d4f"
                    size="24rpx"
                    class="delete-icon"
                    @click="removeRow(index)"
                  />
                </view>
              </view>

              <!-- 新增行按钮 -->
              <view class="add-row" @click="addRow">
                <u-icon name="plus" color="#8c8c8c" size="32rpx" />
                <view class="add-text">新增缺陷记录
                </view>
              </view>
            </view>
          </view>
        </scroll-view>

        <!-- 底部按钮区 -->
        <view class="popup-footer" id="footer">
          <u-button
            @click="showDefects = false"
            type="default"
            class="footer-btn cancel-btn"
            :style="{width: '160rpx'}"
          >
            取消
          </u-button>
          <u-button
            type="primary"
            class="footer-btn confirm-btn"
            :style="{width: '160rpx'}"
            @click="confirmDefectList"
          >
            确认
          </u-button>
        </view>
      </view>
    </u-popup>

  </view>
</template>

<script lang="ts">

import PageHead from "@/components/lanju/page-head/index.vue";
import LjListRow from "@/components/lanju/lj-list-row/index.vue";
import JPicker from "@/components/J-Picker/jPicker.vue";
import {getCheckBpList, getQcDefectTypeClassList, submitCheckResult} from "@/pages/quality/BpCheck/model";
import {BasePage} from "@/components/base/page";
import {Component} from "vue-property-decorator";
import {removeLeadingZeros} from "@/utils/tool";
import {session} from "@/store/modules/session";
import { date } from '@/utils/filter';

@Component({
  methods: { removeLeadingZeros },
  components: {
    JPicker,
    LjListRow,
    PageHead
  },
})

export default class checkBp extends BasePage {
  userinfo: any = uni.getStorageSync('userinfo');
  maxDate = new Date().getFullYear()+1 + "-" +(new Date().getMonth()+1) + "-" + new Date().getDate()

  form = {
    checkDate:undefined,
    materialCode:undefined,
    materialName:undefined,
    incomeBatchNo:undefined,
    checkNum:undefined,
    badNum:undefined,
    isQualified:undefined,
    badItem:undefined,
    remark:undefined,
    createBy: this.userinfo.userName,
    createUserName: this.userinfo.nickName,
    factoryCode: session.FactoryCode,
    defectList:[]
  }

  resetForm = {
    checkDate:undefined,
    materialCode:undefined,
    materialName:undefined,
    incomeBatchNo:undefined,
    checkNum:undefined,
    badNum:undefined,
    isQualified:undefined,
    badItem:undefined,
    remark:undefined,
    createBy: this.userinfo.userName,
    createUserName: this.userinfo.nickName,
    factoryCode: session.FactoryCode,
    defectList:[]
  }

  showCalendar = false
  showList = false
  listHeight = 500
  list = []
  optionResults =[
    { key:"合格", value: "Y" },
    { key:"不合格", value: "N" },
  ]
  optionDefects = []

  rules = {
    checkDate:"请选择日期",
    materialCode:"请选择物料",
    checkNum:"请填写检查数量",
    isQualified:"请选择是否合格"
  }

  showDefects = false

  tableHeight = 300

  defectList = []

  defectIndex = 0

  onReady() {
    getQcDefectTypeClassList(
      {defectCode:"20240822001",pageSize:100}
    ).then(res=>{
      if (res){
        for (const item of res.rows){
          if (item.remark === "白坯专用"){
            this.optionDefects.push(item)
          }
        }
      }
    })
  }

  clickItem(e){
    this.form.materialCode = this.list[e].materialCode
    this.form.materialName = this.list[e].materialName
    setTimeout(()=>{
      this.showList = false
    },200)
  }

  changeDate(e){
    this.form.checkDate = e.result;
    this.clearMaterial()
    getCheckBpList(this.form).then(res=>{
      this.list = res
    })
  }


  clearDate(){
    this.form.checkDate = ""
    this.clearMaterial()
  }

  clearMaterial(){
    this.form.materialCode = ""
    this.form.materialName = ""
  }

  clickShowList(){
    if (!this.form.checkDate){
      uni.showToast({
        title: '请选择日期',
        icon: 'none',
      });
      return;
    }
    this.showList = true
  }

  submit(){
    for (const key in this.form){
      if (!this.form[key] && this.rules[key]){
        uni.showToast({
          title: this.rules[key],
          icon: 'none',
        });
        return;
      }
    }

    //不合格
    if (this.form.isQualified === "N" && this.defectList.length === 0){
      uni.showToast({
        title: "请填写不良项",
        icon: 'none',
      });
    }

    this.form.defectList = this.defectList

    submitCheckResult(this.form).then(res=>{
      if (res.code === 200){
        uni.showToast({
          title: "提交成功",
          icon: 'success',
          mask: true,
          duration: 1000
        });
        setTimeout(() => {
          this.form = this.resetForm;
          this.defectList = []
        }, 1000);
      }
    })

  }

  selectIsQualified(res : any){
    this.form.isQualified = res.pickerName.value
    if (this.form.isQualified === "Y"){
      this.form.badNum = 0
    }else {
      this.form.badNum = undefined
    }
  }

  selectBadItem(res : any){
    this.defectList[this.defectIndex].badItem = res.pickerName.id
  }

  clickDefectsIndex(index){
    console.log(index)
    this.defectIndex = index
  }

  checkShowDefects(){
    this.showDefects = true
    this.calcTableHeight()
  }

  addRow(){
    this.defectList.push({ quantity: undefined, badItem: undefined });
  }


  // 计算表格滚动区域高度
  calcTableHeight() {
    //等待页面加载完成
    this.$nextTick(() => {
      const query = uni.createSelectorQuery().in(this);
      query
        .select('#popup-content')
        .boundingClientRect((data) => {
          this.tableHeight = data.height
        })
        .exec();
    });

  }

  removeRow(index) {
    if (this.defectList.length <= 1) {
      uni.showToast({ title: '至少保留一条记录', icon: 'none', duration: 1500 });
      return;
    }
    this.defectList.splice(index, 1);
  }

  confirmDefectList(){
    if (this.defectList.length === 0){
      uni.showToast({ title: '无缺陷记录', icon: 'none', duration: 1500 });
      return;
    }
    let quantity = 0
    let i = 1
    for (const item of this.defectList){
      if (!item.quantity){
        uni.showToast({ title: '第'+i+'未填写缺陷数量', icon: 'none', duration: 1500 });
        return;
      }

      if (!item.badItem){
        uni.showToast({ title: '第'+i+'未选择缺陷', icon: 'none', duration: 1500 });
        return;
      }
      quantity = quantity + item.quantity
      item.badNum = item.quantity
      item.defectCode = "20240822001"
      item.defectSubclass = "A类"

      i++;
    }
    this.form.badNum = quantity

    this.showDefects = false

  }



}
</script>

<style scoped lang="scss">
.list {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 20rpx 20rpx 25rpx;
  border-radius: 10rpx;
  color: #8d8989;

  .list-item {
    padding:  20rpx;
    margin-bottom: 10rpx;
  }

  /* 奇数行背景色 */
  .list-item:nth-child(odd) {
    background-color: #ffffff;
  }

  /* 偶数行背景色 */
  .list-item:nth-child(even) {
    background-color: #f5f5f5;
  }

  .list-item:hover{
    box-shadow: 0 0 0 3px #0c7bf3;
  }
}

::v-deep .list-item {
  width: 100% !important;
}

.popup-content {
  box-sizing: border-box;
}

.table-scroll {
  border-radius: 8rpx;
  background-color: #fafafa;
  margin-bottom: 30rpx;
}

.table {
  width: 100%;
}

.table-header {
  display: flex;
  background-color: #e8f4f8;
  border-radius: 8rpx 8rpx 0 0;
  height: 80rpx;
  line-height: 80rpx;
}

.table-th {
  text-align: center;
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.table-body {
  background-color: #fff;
}

.table-tr {
  display: flex;
  align-items: center;
  height: 100rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.table-td {
  padding: 0 20rpx;
  box-sizing: border-box;
  text-align: center;
  border: 1rpx solid #e5e5e5;
  line-height: 75rpx;
}

.input-item {
  width: 100%;
  border-radius: 8rpx;
  border: 1rpx solid #e5e5e5;
  padding: 0 16rpx;
  box-sizing: border-box;
}

.delete-icon {
  cursor: pointer;
}

.add-row {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100rpx;
  background-color: #fafafa;
  border-radius: 0 0 8rpx 8rpx;
  cursor: pointer;
}

.add-text {
  font-size: 28rpx;
  color: #8c8c8c;
  margin-left: 16rpx;
}

.popup-footer {
  display: flex;
  justify-content: center;
  gap: 40rpx;
}

.footer-btn {
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
}

.cancel-btn {
  border: 1rpx solid #e5e5e5;
  color: #333;
}

.confirm-btn {
  background-color: #1989fa;
  color: #fff;
}

</style>