<template>
  <div class="app-container">
    <el-card>
      <div class="tabButtonWrap">
        <div
          v-for="(item,$index) in processOption"
          :key="item.id"
          class="tabButton"
          :class="{activeTab:activeIndex===$index}"
          @click="changeIndex(item,$index)"
        >
          {{item.name}}
        </div>
      </div>
      <el-table
        :data="subPlanList"
        fit
        style="width: 100%"
        height="100"
        stripe
        border
        v-el-height-adaptive-table="{bottomOffset: 50}"
      >
        <el-table-column type="index" width="50"/>
        <el-table-column label="子计划编号" min-width="70px" show-overflow-tooltip>
          <template slot-scope="scope">{{scope.row.number}}</template>
        </el-table-column>
        <el-table-column label="产品名称" min-width="120px" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.product_.name }}</template>
        </el-table-column>
        <el-table-column label="产品型号">
          <template slot-scope="scope">{{ scope.row.product_.specification }}</template>
        </el-table-column>
        <el-table-column label="子工序" min-width="120px" show-overflow-tooltip>
          <template slot-scope="scope" v-if="scope.row.steps">
            <el-tag v-for="item in scope.row.steps"
                    :key="item.number"
                    :label="item.name"
                    :value="item.number">{{item.name}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="生产车间">
          <template slot-scope="scope">{{ scope.row.workshop_.name }}</template>
        </el-table-column>
        <el-table-column label="生产数量" prop="count">
        </el-table-column>
        <el-table-column label="开工时间" prop="start_date">
        </el-table-column>
        <el-table-column label="完工时间" prop="end_date">
        </el-table-column>
        <el-table-column label="首件确认状态">
          <template slot-scope="scope">
            <span v-if="scope.row.leader_1!==null&&scope.row.leader_2!==null&&scope.row.leader_3!==null">已完成</span>
            <span v-else>未完成</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="120px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-link
              v-if="checkPermission(['first_test'])&&scope.row.first_test===null"
              type="primary"
              @click="handleTest(scope)"
            >
              首件检验
            </el-link>
            <el-link
              v-else-if="checkPermission(['first_test'])&&scope.row.first_test!==null&&!scope.row.first_test_.is_submited"
              type="primary"
              @click="handleTestContinue(scope)"
            >
              检验
            </el-link>
            <el-link
              v-else-if="checkPermission(['first_audit'])&&scope.row.first_test_.is_submited&&(scope.row.leader_1===null||scope.row.leader_2===null||scope.row.leader_3===null)"
              type="primary"
              @click="handleSelectclick(scope,'0')"
            >
              首件审批
            </el-link>
            <el-link
              v-else-if="scope.row.leader_1!==null&&scope.row.leader_2!==null&&scope.row.leader_3!==null"
              type="primary"
              @click="handleSelectclick(scope,'1')"
            >
              查看
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getsList"
      />
    </el-card>
    <!--物料检查表&&-->
    <el-dialog title="首件确认检查表" :close-on-click-modal="false" :visible.sync="listVisible">
      <el-select style="width: 100%" v-model="recordForm" placeholder="请选择" @change="recordFormChange">
        <el-option
          v-for="item in recordFormList"
          :key="item.name"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="listVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="selectedRecordForm()">填写检查项目</el-button>
      </div>
    </el-dialog>
    <!--检查表显示-->
    <el-dialog
      width="60%"
      :title="formName"
      :visible.sync="recordVisible"
      :close-on-click-modal="false"
      @close="recordCancel"
    >
      <customForm
        v-if="recordVisible"
        :results="fieldList"
        :hasPicture="hasPicture"
        :formID="recordForm"
        :wproduct="recordFormQuery.material"
        :recordId="recordId"
        :isDisabled="isDisabled"
        :isMidTesting="is_midtesting"
        @recordSubmit="recordSubmit"
        @recordSave="recordSave"
        @recordCancel="recordCancel"
      />
    </el-dialog>
    <!--已完成检查表查后的审核-->
    <el-dialog
      title="首件确认审核"
      :visible.sync="reviewVisible"
      :close-on-click-modal="false"
    >
      <el-row>
        <el-col v-for="item in fieldList" :key="item.id+item.id" :span="12">
          <div class="items" v-if="item.field_type!=='draw'&&item.field_value!==null&&item.field_value!==''">
            <span class="itemLabel">{{item.field_name}}：</span>
            <span>{{item.field_value}}</span>
          </div>
        </el-col>
        <el-col :span="12" v-if="achieve">
          <div class="items">
            <span class="itemLabel">工序负责人：</span>
            <span>{{leader_1}}</span>
          </div>
        </el-col>
        <el-col :span="12" v-if="achieve">
          <div class="items">
            <span class="itemLabel">技术负责人：</span>
            <span>{{leader_2}}</span>
          </div>
        </el-col>
        <el-col :span="12" v-if="achieve">
          <div class="items">
            <span class="itemLabel">总检：</span>
            <span>{{leader_3}}</span>
          </div>
        </el-col>
        <el-col :span="12" v-if="achieve">
          <div class="items">
            <span class="itemLabel">首件检查时间：</span>
            <span>{{update_time}}</span>
          </div>
        </el-col>
        <el-col :span="12" v-if="achieve">
          <div class="items">
            <span class="itemLabel">首件审批时间：</span>
            <span>{{first_sign_time}}</span>
          </div>
        </el-col>
        <el-col v-for="item in fieldList" :key="item.id" :span="24">
          <div class="items" v-if="item.field_type==='draw'" style="height: 400px">
            <span class="itemLabel">{{item.field_name}}：</span>
            <img style="width: 45%;vertical-align: text-top;" :src="'http://49.232.14.174:2222'+item.field_value"/>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="items">
            <span class="itemLabel">检验结果：</span>
            <span v-if="is_testok">检验合格</span>
            <span v-else>检验不合格</span>
          </div>
        </el-col>
      </el-row>
      <el-row class="reviewWrap" v-if="!achieve">
        <div class="reviewBlock">
          <span>工序负责人:</span>
          <div class="directorName">{{leader_1}}</div>
          <span class="reviewBtn" @click="directorConfirm('leader_1')">人脸验证</span>
        </div>
        <div class="reviewBlock">
          <span>技术负责人:</span>
          <div class="directorName">{{leader_2}}</div>
          <span class="reviewBtn" @click="directorConfirm('leader_2')">人脸验证</span>
        </div>
        <div class="reviewBlock">
          <span>总检:</span>
          <div class="directorName">{{leader_3}}</div>
          <span class="reviewBtn" @click="directorConfirm('leader_3')">人脸验证</span>
        </div>
      </el-row>
    </el-dialog>
    <el-dialog :visible.sync="limitedPhoto" @close="closeCamera" id="loginFaceWrap">
      <div style="font-size: 28px;color: #333333;text-align: center;font-weight: bold;">审核人员确认</div>
      <div class="testTracking">
        <faceLogin v-if="limitedPhoto" ref="faceTracking" name="faceLogin" @func="getMsgFormSon"></faceLogin>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import checkPermission from "@/utils/permission";
  import Pagination from "@/components/Pagination";
  import customForm from '@/components/customForm/index';
  import faceLogin from '@/components/faceLogin/review.vue';
  import {getProcessList,getrecordformList} from "@/api/mtm";
  import {getsubplanList} from "@/api/wpm";
  import {firstTestInit,firstAudit} from "@/api/pm";
  import {getTestRecordItem,putTestRecordItem,subTestRecordItem} from "@/api/qm";

  export default {
    name: "firstCheck",
    inject:['reload'],
    components: {Pagination,faceLogin,customForm},
    data() {
      return {
        count: 0,
        activeIndex: 0,
        fieldList: [],
        subPlanList: [],
        processOption: [],
        recordFormList: [],
        listQuery:{
          page:1,
          page_size:20,
          process: null,
        },
        recordFormQuery:{
          type:50,
          enabled:true,
          material:null
        },
        planId:null,
        leader:null,
        recordId: null,
        leader_1: null,
        leader_2: null,
        leader_3: null,
        recordForm:null,
        achieve:false,
        hasPicture:false,
        isDisabled: false,
        listLoading:false,
        listVisible:false,
        limitedPhoto:false,
        reviewVisible:false,
        recordVisible:false,
        is_midtesting:false,
        is_testok:false,
        formName:'首件确认检查表',
        update_time:'',
        first_sign_time:'',
      }
    },
    methods: {
      checkPermission,
      //工序渲染
      getProcessList() {
        let that = this;
        getProcessList({page: 0}).then((response) => {
          if (response.data) {
            that.processOption = response.data;
            that.listQuery.process = response.data[0].id;
            that.getTableData();
          }
        });
      },

      //工序转换
      changeIndex(item,index) {
        this.activeIndex = index;
        this.listQuery.process = item.id;
          this.getTableData();
      },

      //获取table数据
      getTableData() {
        this.listLoading = true;
        this.listQuery.production_plan = this.id;
        getsubplanList(this.listQuery).then((response) => {
          if (response.data) {
            this.subPlanList = response.data.results;
            this.count = response.data.count;
          }
          this.listLoading = false;
        });
      },

      //分页
      getsList(){
        this.getTableData
      },

      //第一次点击首件检验
      handleTest(scope){
        let that = this;
        that.planId = scope.row.id;//子生产计划ID
        that.recordFormQuery.material = scope.row.product;
        that.recordForm = null;
        getrecordformList(that.recordFormQuery).then((response) => {
          if (response.data) {
            that.recordformList = response.data.results;
            if (that.recordformList.length === 1) {
              that.recordForm = that.recordformList[0].id;
              that.formName = that.recordformList[0].name;
              that.selectedRecordForm();
            } else {
              //弹出列表选择框
              that.listVisible = true;
            }
          }
        });
      },

      //首件审批
      handleSelectclick(scope,index){
        let that = this;
        this.reviewVisible = true;
        that.planId = scope.row.id;
        that.leader_1 = scope.row.leader_1_?scope.row.leader_1_.name:null;
        that.leader_2 = scope.row.leader_2_?scope.row.leader_2_.name:null;
        that.leader_3 = scope.row.leader_3_?scope.row.leader_3_.name:null;
        that.first_sign_time = scope.row.first_sign_time?scope.row.first_sign_time:'';
        getTestRecordItem(scope.row.first_test).then((res) => {
          that.formName = res.data.form_.name;
          that.is_testok = res.data.is_testok;
          that.update_time = res.data.update_time;
          let fieldList = res.data.record_data;
          that.fieldList = [...fieldList];
          let arr = fieldList.filter(item => {
            return item.field_type === 'draw'
          });
          if (arr.length > 0) {
            that.hasPicture = true;
          }
          that.$nextTick(() => {
            if(index==='1'){
              this.achieve = true;
            }else{
              this.achieve = false;
            }
            that.reviewVisible = true;
          });
        })
      },

      //选择物料检查表
      recordFormChange() {
        let that = this;
        let arr = this.recordFormList.filter(item => {
          return item.id === that.recordForm;
        });
        that.formName = arr[0].name;
      },

      //根据选择的表，渲染检查项目
      selectedRecordForm() {
        let that = this;
        this.listVisible = false;
        that.fieldList = [];
        if (that.recordForm != "") {
          firstTestInit(that.planId,{ form: that.recordForm}).then((response) => {
            if (response.code===200) {
              that.hasPicture = false;
              that.recordId = response.data.id;//记录id
              that.formName = response.data.form_.name;//引用的检查表id
              let fieldList = response.data.record_data;
              that.fieldList = [...fieldList];
              let arr = fieldList.filter(item => {
                return item.field_type === 'draw'
              });
              if (arr.length > 0) {
                that.hasPicture = true;
              }
              that.$nextTick(() => {
                that.recordVisible = true;
              });
            }
          });
        } else this.$message.error("请选择检查表！");
      },

      //第一次保存提交检查项目
      recordCancel() {
        this.recordVisible = false;
        this.listVisible = false;
        this.getTableData();
      },

      /*关闭相机*/
      closeCamera () {
        this.$refs.faceTracking.closeCamera();
        let video = document.getElementById('video');
        let stream = video.srcObject;
        // console.log(stream);
        let tracks = stream.getTracks();
        tracks.forEach(track => {
          track.stop()
        });
        video.srcObject = null;
      },

      //保存首件检查
      recordSave(value) {
        let that = this;
        let id = value.id;
        let params = {};
        params.record_data = value.record_data;
        params.is_testok = value.is_testok;
        putTestRecordItem(id, params).then((res) => {
          if (res.code >= 200) {
            that.recordVisible = false;
            that.getTableData();
          } else {
            that.$message.error(res.msg)
          }
        }).catch((err) => {
          that.$message.error(err)
        });
      },

      //提交首件检查
      recordSubmit(value) {
        let that = this;
        let id = value.id;
        let params = {};
        params.record_data = value.record_data;
        params.is_testok = value.is_testok;
        putTestRecordItem(id, params).then((res) => {
          if (res.code >= 200) {
            subTestRecordItem(id, params).then((res) => {
              if (res.code >= 200) {
                that.recordVisible = false;
                that.getTableData();
              }
            });
          } else {
            that.$message.error(res.msg)
          }
        }).catch((err) => {
          that.$message.error(err);
        });
      },

      //再次点击首件检验
      handleTestContinue(scope) {
        let that = this;
        that.fieldList = [];
        that.recordVisible = false;
        that.planId = scope.row.id;
        that.recordId = scope.row.first_test;
        that.recordForm = scope.row.first_test_.form;
        getTestRecordItem(scope.row.first_test).then((res) => {
          that.formName = res.data.form_.name;
          let fieldList = res.data.record_data;
          that.fieldList = [...fieldList];
          let arr = fieldList.filter(item => {
            return item.field_type === 'draw'
          });
          if (arr.length > 0) {
            that.hasPicture = true;
          }
          that.$nextTick(() => {
            that.recordVisible = true;
          });
        })
        /*getrffieldList({form: this.recordform,enabled:true, page: 1, page_size: 100}).then((response) => {
          if (response.data) {
            that.hasPicture = false;
            let fieldList = response.data.results;
            that.fieldList = [...fieldList];
            let arr = fieldList.filter(item => {
              return item.field_type === 'draw'
            });
            if (arr.length > 0) {
              that.hasPicture = true;
            }

          }
        });*/
      },

      //点击人脸验证
      directorConfirm(index){
        this.leader = index;
        this.limitedPhoto = true;
      },

      //获取人脸数据
      getMsgFormSon(data){
        let that =this;
        if(data.token!==''&&data.token!==null&&data.token!==undefined){
          if(that.leader==='leader_1'){
            that.leader_1=data.name;
          }else if(that.leader==='leader_2'){
            that.leader_2=data.name;
          }else if(that.leader==='leader_3'){
            that.leader_3=data.name;
          }
          firstAudit(that.planId,{leader:that.leader ,token : data.token}).then(res=>{
            this.limitedPhoto = false;
            if(res.code===200){
              this.limitedPhoto = false;
              if(that.leader_1!==null&&that.leader_2!==null&&that.leader_3!==null){
                this.reviewVisible = false;
              }
             /* let firstTestIndex = sessionStorage.getItem('firstTestIndex');
              let firstTestProcess = sessionStorage.getItem('firstTestProcess');
              if(firstTestIndex){
                sessionStorage.removeItem('firstTestIndex');
                sessionStorage.setItem('firstTestIndex',this.activeIndex);
              }else{
                sessionStorage.setItem('firstTestIndex',this.activeIndex);
              }
              if(firstTestProcess){
                sessionStorage.removeItem('firstTestProcess');
                sessionStorage.setItem('firstTestProcess',this.listQuery.process);
              }else{
                sessionStorage.setItem('firstTestProcess',this.listQuery.process);
              }*/
              that.getTableData();
              // that.reload();
            }
          })
        }
      },
    },
    mounted() {
      this.getProcessList();
    },
  }
</script>

<style scoped>
  .tabButtonWrap{
    display: flex;
    margin-bottom: 2px;
    border-bottom: 1px solid #EBEEF5;
  }
  .tabButton{
    height: 40px;
    width: 100px;
    color: #555555;
    line-height: 40px;
    text-align: center;
    border: 1px solid #EBEEF5;
    border-radius: 10px 10px 0 0;
  }
  .activeTab {
    color: #FFFFFF;
    font-weight: bold;
    background: #409EFF;
  }
  .reviewWrap{
    display: flex;
    font-size: 16px;
    justify-content: flex-end;
  }
  .reviewBlock{
    display: flex;
    flex-direction: column;
    margin-right: 40px
  }
  .directorName{
    height: 30px;
  }
  .reviewBtn{
    width: 80px;
    height: 35px;
    font-size: 15px;
    line-height: 33px;
    text-align: center;
    border: 1px solid #409eff;
    border-radius: 5px;
    /*background: #409eff;*/
    color: #409eff;
  }
  .items {
    height: 35px;
    line-height: 35px;
    padding-left: 20px;
  }

  .itemLabel {
    font-size: 14px;
    color: #606266;
    font-weight: 600;
  }
</style>
