<template>
  <view class="list-page">
    <!--  页面头  -->
    <page-head title="留样复检" />

    <u-form id="form" class="page-form" ref="form" label-width="180rpx">

      <u-form-item label="复检间隔">
        <jPicker sureColor="#ff0000" moren="请选择复检间隔" @bindpicker="selectSearchFlag" showKey="key" valKey="value" :val="queryParams.searchFlag" :options="typeOptions" />
      </u-form-item>

      <u-form-item label="工单号" label-width="18vw">
        <u-search placeholder="请输入工单号" :focus="true" v-model="queryParams.workOrderCodeSap" @search="getList" :show-action="false"></u-search>
      </u-form-item>
      <u-form-item label="批次号" label-width="18vw">
        <u-search placeholder="请输入批次号" :focus="true" v-model="queryParams.incomeBatchNo" @search="getList" :show-action="false"></u-search>
      </u-form-item>
      <u-form-item label="物料名称" label-width="18vw">
        <u-search placeholder="请输入物料名称" :focus="true" v-model="queryParams.materialName" @search="getList" :show-action="false"></u-search>
      </u-form-item>

    </u-form>


    <scroll-view id="list" scroll-y="true" :style="{ height: listHeight + 'px' }" @scrolltolower="onScrollToLower" :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" >
            <lj-list-row label="物料名称:" :value="item.materialName" />
            <lj-list-row label="来料批次号:" :value="item.incomeBatchNo" />
            <lj-list-row label="工单号:" :value="item.workOrderCodeSap" />
            <lj-list-row label="留样时间:" :value="formatDate(item, 0, '未留样')" />
            <view>
              <lj-list-row label="第一次复检:" :value="formatDate(item,1, '未复检')" />
              <lj-list-row label="第二次复检:" :value="formatDate(item,2, '未复检')" />
              <lj-list-row label="第三次复检:" :value="formatDate(item,3, '未复检')" />
              <lj-list-row label="间隔6月复检:" :value="formatDate(item,6, '未复检')" />
              <lj-list-row label="间隔1年复检:" :value="formatDate(item,12, '未复检')" />
            </view>




            <view class="righttitle">
              <view @click.stop="handelOption(item, 1)" v-if="showCheckButton(item,1)" class="boder-icon-rigth"> 第一次复检</view>
              <view @click.stop="handelOption(item, 2)" v-if="showCheckButton(item, 2)" class="boder-icon-rigth"> 第二次复检</view>
              <view @click.stop="handelOption(item, 3)" v-if="showCheckButton(item,3)" class="boder-icon-rigth"> 第三次复检</view>
              <view @click.stop="handelOption(item, 6)" v-if="showCheckButton(item,6)" class="boder-icon-rigth"> 间隔6月复检</view>
              <view @click.stop="handelOption(item, 12)" v-if="showCheckButton(item,12)" class="boder-icon-rigth"> 间隔1年复检</view>
            </view>
          </view>
        </view>
        <view v-else> 暂无数据 </view>
      </u-form>
    </scroll-view>

    <!-- 弹窗表单 -->
    <u-popup  v-model="showPopup" mode="center"  @close="cancel" width="580rpx" :customStyle="popupStyle">

      <u-form class="page-form">
        <u-form-item required  label="是否合格:" label-width="20vw">
          <u-radio-group v-model="checkResult.isQualified" >
            <u-radio v-for="(item, index) in resultsOption" :key="index" :name="item.value" >
              {{ item.key }}
            </u-radio>
          </u-radio-group>
        </u-form-item>

        <u-form-item label="检验结果描述:" labelPosition="top">
          <u-input type="textarea" placeholder="请填写描述" v-model="checkResult.desc" :show-action="false"></u-input>
        </u-form-item>

        <view v-if="checkResult.isQualified === 'N'">
          <u-form-item required  label="是否生成OA流程:" label-width="35vw">
            <u-radio-group  v-model="checkResult.isApplyOa" >
              <u-radio v-for="(item, index) in yesOrNotOption" :key="index" :name="item.value" >
                {{ item.key }}
              </u-radio>
            </u-radio-group>
          </u-form-item>

          <view v-if="checkResult.isApplyOa === '0'">

            <u-form-item required label="生产数量:" label-width="20vw">
              <u-input placeholder="请填写生产数量" v-model="checkResult.quantity" :show-action="false"></u-input>
            </u-form-item>

            <u-form-item required label="申请部门:" label-width="20vw">
              <jPicker sureColor="#ff0000" moren="请选择" showKey="ymdTypeName" @bindpicker="selectApplyDept" valKey="ymdType" :val="checkResult.applyDept" :options="deptList" />
            </u-form-item>

            <u-form-item required label="发现地点:" label-width="20vw">
              <u-input placeholder="请填写发现地点" v-model="checkResult.findPlace" :show-action="false"></u-input>
            </u-form-item>

            <u-form-item required  label="是否供应商问题:" label-width="35vw">
              <u-radio-group v-model="checkResult.isSupplierIssue" >
                <u-radio v-for="(item, index) in yesOrNotOption" :key="index" :name="item.value" >
                  {{ item.key }}
                </u-radio>
              </u-radio-group>
            </u-form-item>

            <u-form-item required label="异常范围:" label-width="20vw">
              <jPicker sureColor="#ff0000" moren="请选择" showKey="ymdTypeName" @bindpicker="selectExcRange" valKey="ymdType" :val="checkResult.excRange" :options="excRangeList" />
            </u-form-item>

            <u-form-item required label="所属车间:" label-width="20vw">
              <jPicker sureColor="#ff0000" moren="请选择" showKey="ymdTypeName" @bindpicker="selectWorkshop" valKey="ymdType" :val="checkResult.workshop" :options="workshopList" />
            </u-form-item>

            <u-form-item required  label="是否需要主管审核:" label-width="35vw">
              <u-radio-group v-model="checkResult.isNeedAudit" >
                <u-radio v-for="(item, index) in yesOrNotOption" :key="index" :name="item.value" >
                  {{ item.key }}
                </u-radio>
              </u-radio-group>
            </u-form-item>

            <u-form-item :required="checkResult.isNeedAudit === '0'" label="QC主管:" label-width="20vw">
              <jPicker sureColor="#ff0000" moren="请选择" @bindpicker="selectQcManager" showKey="userName" valKey="userCode" :val="checkResult.qcManager" :options="managerList" />
            </u-form-item>

            <u-form-item required  label="质量主管:" label-width="20vw">
              <jPicker sureColor="#ff0000" moren="请选择" @bindpicker="selectQtManager" showKey="userName" valKey="userCode" :val="checkResult.qtManager" :options="managerList" />
            </u-form-item>

          </view>

          <u-form-item :required="checkResult.isQualified === 'N'" label="不合格原因:" labelPosition="top">
            <u-input type="textarea" placeholder="请填写不合格原因" v-model="checkResult.reason" :show-action="false"></u-input>
          </u-form-item>
        </view>



        <u-form-item label="备注:" label-width="20vw">
          <u-input placeholder="请填写备注" v-model="checkResult.remark" :show-action="false"></u-input>
        </u-form-item>
      </u-form>
      <view>
        <!-- 按钮区域 -->
        <view class="btn-group">
          <u-button
            @click="cancel"
            shape="circle"
            type="info"
          >
            取消
          </u-button>
          <u-button
            @click="submitForm"
            shape="circle"
            type="primary"
          >
            提交
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script lang="ts">
import {Component} from 'vue-property-decorator';
import {BasePage} from '@/components/base/page';
import {
  getDeptList,
  getExcRangeList,
  getManagerList,
  getQcWaitCheckSampleTaskList,
  getWorkshopList,
  submitCheckSampleTaskZl0030
} from './model';
import moment from 'moment';
import PageHead from '@/components/lanju/page-head/index.vue';
import LjListRow from '@/components/lanju/lj-list-row/index.vue';
import ljPagination from '@/components/lanju/lj-pagination/index.vue';
import JPicker from "@/components/J-Picker/jPicker.vue";
import {session} from "@/store/modules/session";

@Component({
  components: {
    JPicker,
    LjListRow,
    PageHead,
    ljPagination,
  },
})
export default class SampleCheck extends BasePage {
  listHeight = 500;
  mode = 'date';
  queryParams = {
    pageNum: 1,
    pageSize: 10,
    firstDate: undefined,
    secondDate: undefined,
    thirdDate: undefined,
    searchFlag:"1",
    workOrderCodeSap:undefined,
    incomeBatchNo:undefined,
    materialName:undefined
  };
  total = 0;
  list: any = [];
  userinfo: any = uni.getStorageSync('userinfo');

  showPopup = false

  checkResult = {
    sampleTaskId:undefined,
    isQualified :undefined,
    isApplyOa:undefined,
    quantity:undefined,
    desc:undefined,
    applyDept:undefined,
    findPlace:undefined,
    isSupplierIssue:undefined,
    excRange:undefined,
    workshop:undefined,
    isNeedAudit:undefined,
    qcManager :undefined,
    qtManager :undefined,
    reason :undefined,
    remark :undefined,
    checkTimes:undefined,
    createBy:undefined,
    createUserName:undefined
  }

  rules = {
    quantity:"请填写生产数量",
    applyDept:"请选择申请部门",
    findPlace:"请填写发现地点",
    isSupplierIssue:"请选择是否供应商问题",
    excRange:"请选择异常范围",
    workshop:"请选择所属车间",
    isNeedAudit:"请选择是否需要主管审核",
    qtManager:"请选择质量主管",
  }

  resultsOption =[
    { key:"合格", value: "Y" },
    { key:"不合格", value: "N" },
    { key:"未复检", value: "X" },
  ]

  yesOrNotOption = [
    { key:"是", value: "0" },
    { key:"否", value: "1" },
  ]

  managerList = []

  deptList = []

  excRangeList = []

  workshopList = []

  num = 0

  item = undefined

  popupStyle = {
    top: "5vh",
    height:"90vh"
  }

  typeOptions = [
    { key:"间隔1月", value: "1" },
    { key:"间隔2月", value: "2" },
    { key:"间隔3月", value: "3" },
    { key:"间隔6月", value: "6" },
    { key:"间隔1年", value: "12" },
  ]

  onLoad() {
    this.getList();

    getDeptList().then(res=>{
      this.deptList = res
    })

    getExcRangeList().then(res=>{
      this.excRangeList = res
    })

    getWorkshopList().then(res=>{
      this.workshopList = res
    })

    getManagerList().then(res=>{
      this.managerList = res
    })

  }

  async handelOption(item: any, num: number) {
    this.showPopup = true
    this.item = item
    this.num = num
  }


  showCheckButton(item: any,num: Number){

    if (item.resultList) {
      for (const i of item.resultList){
        if (i.checkTimes === num){
          if (i.qualified === 'X'){
            return true
          }else {
            return false
          }
        }
      }
    }

    const diff = this.timeDifference(item.sampleTime);
    return diff >= num;
  }

  //计算时间差
  timeDifference(time: any) {
    //留样时间戳
    const targetDate = moment(time).toDate(); // 直接转Date对象更高效

    // 2. 获取当前时间和目标时间的年、月
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth();
    const targetYear = targetDate.getFullYear();
    const targetMonth = targetDate.getMonth();

    // 3. 核心计算：结合年份和月份计算总差值
    return (currentYear - targetYear) * 12 + (currentMonth - targetMonth);
  }

  //时间转换
  formatDate(item: any, num: number, msg: string) {
    if (num === 0){
      return moment(item.sampleTime).format('YYYY-MM-DD HH:mm:ss');
    }

    if (!item.resultList) {
      return msg;
    }

    for (const i of item.resultList){
      if (i.checkTimes === num){
        let str = ''
        if (i.qualified === 'X'){
          str = '(未复检)'
        }
        return moment(i.createTime).format('YYYY-MM-DD HH:mm:ss') + str;
      }
    }

    return msg;

  }

  async getList() {
    getQcWaitCheckSampleTaskList(this.queryParams).then(res=>{
      this.list = res.rows
      this.total = res.total
    })

  }

  onReady() {
    //等待页面加载完成
    this.$nextTick(() => {
      let buttonTop = 0;
      //获取底部按钮信息
      const query = uni.createSelectorQuery().in(this);
      const screenHeight = uni.getSystemInfoSync().screenHeight;
      //获取列表信息
      query
        .select('#list')
        .boundingClientRect((data) => {
          //获取列表到顶部距离
          const listTop = data.top;
          //
          this.listHeight = screenHeight - listTop - 10;
        })
        .exec();
    });
  }

  onScrollToLower() {
    if (this.total === this.list.length) {
      return;
    }
    this.queryParams.pageNum = this.queryParams.pageNum + 1;
    getQcWaitCheckSampleTaskList(this.queryParams).then(res=>{
      this.list = this.list.concat(res.rows);
    })
  }

  cancel(){
    this.checkResult = {
      sampleTaskId:undefined,
      isQualified :undefined,
      isApplyOa:undefined,
      quantity:undefined,
      isNeedAudit:undefined,
      qcManager :undefined,
      qtManager :undefined,
      applyDept:undefined,
      findPlace:undefined,
      isSupplierIssue:undefined,
      excRange:undefined,
      workshop:undefined,
      reason :undefined,
      remark :undefined,
      checkTimes:undefined,
      createBy:undefined,
      createUserName:undefined,
      desc:undefined
    }
    this.showPopup = false
  }

  // 提交表单
  async submitForm() {

    if (!this.checkResult.isQualified){
      uni.showToast({
        title: "请选择是否合格",
        icon: 'none',
        mask: true,
        duration: 1000
      });
      return;
    }
    if (this.checkResult.isQualified === "N"){

      if (!this.checkResult.isApplyOa){
        uni.showToast({
          title: "请选择是否生成OA流程",
          icon: 'none',
          mask: true,
          duration: 1000
        });
        return;
      }
      if (this.checkResult.isApplyOa === "0"){
        for (const key in this.checkResult){
          if (this.rules[key] && !this.checkResult[key]){
            uni.showToast({
              title: this.rules[key],
              icon: 'none',
              mask: true,
              duration: 1000
            });
            return;
          }
        }
        if (this.checkResult.isNeedAudit === "0" && !this.checkResult.qcManager){
          uni.showToast({
            title: "请选择QC主管",
            icon: 'none',
            mask: true,
            duration: 1000
          });
          return;
        }

      }

      if (!this.checkResult.reason){
        uni.showToast({
          title: "请填写不合格原因",
          icon: 'none',
          mask: true,
          duration: 1000
        });
        return;
      }
    }

    this.checkResult.sampleTaskId = this.item.id
    this.checkResult.checkTimes = this.num
    this.checkResult.createBy = session.userName
    this.checkResult.createUserName = this.userinfo.nickName

    const afterAction = () => {
      uni.showToast({
        title: "提交成功",
        icon: 'success',
        mask: true,
        duration: 1000
      });
      setTimeout(() => {
        this.cancel();
        this.getList();
      }, 1000);
    };

    submitCheckSampleTaskZl0030(this.checkResult).then(afterAction);


    // updateQcCheckSampleTask(po)
    //   .then(res => {
    //
    //
    //     if (this.checkResult.isQualified === "N") {
    //     } else {
    //       afterAction();
    //     }
    //   });
  }

  selectApplyDept(res){
    this.checkResult.applyDept = res.pickerName.ymdType
  }

  selectExcRange(res){
    this.checkResult.excRange = res.pickerName.ymdType
  }

  selectWorkshop(res){
    this.checkResult.workshop = res.pickerName.ymdType
  }

  selectQcManager(res){
    this.checkResult.qcManager = res.pickerName.userCode
  }

  selectQtManager(res){
    this.checkResult.qtManager = res.pickerName.userCode
  }

  selectSearchFlag(res){
    this.queryParams.searchFlag = res.pickerName.value
    this.getList();
  }



}
</script>
<style lang="scss" scoped>
.list-page {
  background: #f2f2f2 linear-gradient(0deg, #f2f2f2 0%, #f8262c 51%, #d9001b 100%) no-repeat;
  background-size: 100% 600rpx;
  padding: 118rpx 30rpx 0;
  min-height: 100%;
}



.list {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 20rpx 20rpx 25rpx;
  border-radius: 10rpx;
  box-shadow: 0 0 20rpx 0 rgba(128, 128, 128, 0.2);
  color: #8d8989;

  .list-item {
    padding: 20rpx;
  }

  .righttitle {
    display: flex;
    justify-content: flex-end;

    .boder-icon-rigth {
      font-size: 30rpx;
      border-radius: 5px;
      border: 1rpx solid #fa3534;
      text-align: center;
      background: #fa3534;
      color: #ffffff;
      margin-top: 10px;
      margin-left: 10px;
    }
  }

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

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

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

.btn-group {
  display: flex;
  justify-content: center;
  margin-top: 10rpx;
  margin-bottom: 10rpx;
}
</style>
