<template>
  <div class="app-container">
    <el-tabs type="border-card">
      <el-tab-pane label="待检成品">
        <el-card style="margin-top: 2px">
          <el-table
            v-loading="listLoading"
            :data="wproductList.results"
            border
            fit
            stripe
            highlight-current-row
            max-height="600"
          >
            <el-table-column type="index" width="50"/>
            <el-table-column label="成品名称">
              <template slot-scope="scope">
                {{scope.row.material_.name}}
              </template>
            </el-table-column>
            <el-table-column label="成品编号">
              <template slot-scope="scope">{{ scope.row.number }}</template>
            </el-table-column>
            <el-table-column label="检测状态">
              <template slot-scope="scope">
                {{ actstate_[scope.row.act_state] }}
              </template>
            </el-table-column>
            <el-table-column label="检验员">
              <!--<template slot-scope="scope">-->
                <!--{{ actstate_[scope.row.act_state] }}-->
              <!--</template>-->
            </el-table-column>
            <el-table-column label="所在子工序">
              <template slot-scope="scope">{{ scope.row.step_.name }}</template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="220px">
              <template slot-scope="scope">
                <el-link
                  v-if="checkPermission(['wp_test_init']) &&scope.row.test === null"
                  @click="handleInspection(scope)"
                >
                  检验
                </el-link>
                <el-link
                  v-if="scope.row.test !== null"
                  @click="checkRecord(scope)"
                >
                  检验记录
                </el-link>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="wproductList.count > 0"
            :total="wproductList.count"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.page_size"
            @pagination="getList"
          />
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="已合格成品">
        <el-card style="margin-top: 2px">
          <el-button type="primary" icon="el-icon-plus" @click="handleCreate"
          >批量入库
          </el-button>
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="wproductList1.results"
            border
            fit
            stripe
            highlight-current-row
            max-height="600"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" width="50"/>
            <el-table-column label="成品名称">
              <template slot-scope="scope">
                {{scope.row.material_.name}}
              </template>
            </el-table-column>
            <el-table-column label="成品编号">
              <template slot-scope="scope">{{ scope.row.number }}</template>
            </el-table-column>
            <el-table-column label="检测状态">
              <template slot-scope="scope">
                {{ actstate_[scope.row.act_state] }}
              </template>
            </el-table-column>
            <el-table-column label="检验员">
              <template slot-scope="scope">
                <span v-if="scope.row.update_by_!==null">{{scope.row.update_by_.username}}</span>
                <span v-else>{{scope.row.create_by_.username}}</span>
              </template>
            </el-table-column>
            <el-table-column label="指派订单">
              <template slot-scope="scope" v-if="scope.row.order_">
                {{scope.row.order_.number }}
              </template>
            </el-table-column>
            <el-table-column label="客户">
              <template slot-scope="scope" v-if="scope.row.customer_">
                {{scope.row.customer_.name }}
              </template>
            </el-table-column>
            <el-table-column label="合同">
              <template slot-scope="scope" v-if="scope.row.contract_">
                {{scope.row.contract_.name }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="220px">
              <template slot-scope="scope">
                <el-link
                  v-if="checkPermission(['wp_putins'])"
                  @click="handlePutin(scope)"
                >
                  入库
                </el-link>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="wproductList1.count > 0"
            :total="wproductList1.count"
            :page.sync="listQuery1.page"
            :limit.sync="listQuery1.page_size"
            @pagination="getList1"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>
    <!--物料检查表&&-->
    <el-dialog
      title="物料检查表"
      :close-on-click-modal="false"
      :visible.sync="outerVisible"
    >
      <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="outerVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitrecordform()"
        >
          填写检查项目
        </el-button>
      </div>
    </el-dialog>
    <!--检查表显示-->
    <el-dialog
      width="60%"
      :title="formName"
      :visible.sync="innerVisible"
      :close-on-click-modal="false"
      @close="recordCancel"
    >
      <customForm
        v-if="innerVisible"
        :results="fieldList"
        :hasPicture="hasPicture"
        :formID="recordform"
        :wproduct="wproduct"
        :recordId="recordId"
        @recordSubmit="recordSubmit"
        @recordSave="recordSave"
        @recordCancel="recordCancel"
      />
    </el-dialog>
    <!--检验记录-->
    <el-dialog
      title="检验记录"
      :close-on-click-modal="false"
      :visible.sync="limitedCheckRecord"
    >
      <el-table :data="recordList" border height="400">
        <el-table-column type="index" width="50"/>
        <el-table-column label="表单名称">
          <template slot-scope="scope">{{ scope.row.form_.name }}</template>
        </el-table-column>
        <el-table-column label="检查类型">
          <template slot-scope="scope">
            {{checkTypes[scope.row.type]}}
          </template>
        </el-table-column>
        <el-table-column label="是否提交">
          <template slot-scope="scope">
            <span v-if="scope.row.is_submited">已提交</span>
            <span v-else>未提交</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-link
              v-if="checkPermission(['wp_test_init'])&&!scope.row.is_submited"
              @click="handleInspectionRecord(scope)"
            >
              检验
            </el-link>
            <el-link
              v-if="scope.row.is_submited"
              @click="handleRecordDetail(scope)"
            >
              查看
            </el-link>
            <el-link @click="delTestRecord(scope)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="putin">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="成品入库"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="form">
        <el-form-item label="仓库">
          <el-select
            v-model="form.warehouse"
            style="width: 100%"
            placeholder="请选择仓库"
          >
            <el-option
              v-for="item in WarehouseData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="putin">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="成品批量入库"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisibles"
    >
      <el-form :model="form">
        <el-form-item label="仓库">
          <el-select
            v-model="form.warehouse"
            style="width: 100%"
            placeholder="请选择仓库"
          >
            <el-option
              v-for="item in WarehouseData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibles = false">取 消</el-button>
        <el-button type="primary" @click="putins">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  // import {getOrderList} from "@/api/sam";
  import checkPermission from "@/utils/permission";
  import {getWarehouseList} from "@/api/inm";
  import { getrecordformList, getrffieldList} from "@/api/mtm";
  // import {genTree} from "@/utils";
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import customForm from "@/components/customForm/index";
  import {
    getwproductList,
    wproductTest,
    wproductPutin,
    createputins,
    testInit,
  } from "@/api/wpm";
  import {
    getTestRecord,
    getTestRecordItem,
    putTestRecordItem,
    delTestRecordItem,
    subTestRecordItem,
  } from "@/api/qm";

  const defaultetestitem = {};
  export default {
    components: {Pagination, customForm},
    data() {
      return {
        testitem: defaultetestitem,
        form: {remark: "", warehouse: ""},
        form1: {},
        wproductList: {
          count: 0,
        },
        wproductList1: {
          count: 0,
        },
        wproductList2: {
          count: 0,
        },
        listQuery: {
          page: 1,
          page_size: 20,
        },
        listQuery1: {
          page: 1,
          page_size: 20,
        },
        listQuery2: {
          page: 1,
          page_size: 20,
        },
        actstate_: {
          6: "待复检",
          10: "生产中",
          20: "待检验",
          30: "已合格",
          40: "库存中",
          50: "不合格",
          60: "待成品检验",
        },
        checkTypes: {
          10: "子工序检验",
          20: "工序检验",
          30: "工序复检",
          36: "夹层检验",
          40: "成品检验",
        },
        choice: [
          {value: true, label: "合格"},
          {value: false, label: "不合格"},
        ],
        options: [],
        listLoading: true,
        wproduct: null,
        recordId: null,
        fieldList: null,
        is_testok: "true",
        field: [],
        recordList: [],
        recordformList: [],
        recordform: null,
        fifo_detail: "",
        listQueryrecordform: {
          page: 0,
        },
        hasPicture: false,
        outerVisible: false,
        innerVisible: false,
        dialogFormVisible: false,
        dialogFormVisibles: false,
        limitedCheckRecord: false,
        testrecord: {},
        formName: "检验表",
        WarehouseData: "",

      };
    },
    computed: {},
    watch: {},
    created() {
      this.getList();

      this.getList1();
      // this.getLists();
    },
    methods: {
      checkPermission,
      //待检成品列表
      getList() {
        this.listLoading = true;
        this.listQuery.act_state = 60;
        this.listQuery.material__type = 1;
        getwproductList(this.listQuery).then((response) => {
          if (response.data) {
            this.wproductList = response.data;
          }
          this.listLoading = false;
        });
      },

      //已合格成品
      getList1() {
        this.listQuery1.act_state = 30;
        this.listQuery1.material__type = 1;
        getwproductList(this.listQuery1).then((response) => {
          if (response.data) {
            this.wproductList1 = response.data;
          }
        });
      },

      //成品批量入库
      handleCreate() {
        this.dialogFormVisibles = true;
        this.getWarehouseLists(); //仓库
      },

      //批量入库
      putins() {
        let _this = this;
        _this.mutipID = [];
        this.$refs.multipleTable.selection.forEach((item) => {
          _this.mutipID.push(item.id);
        });
        createputins({
          warehouse: this.form.warehouse,
          wproducts: _this.mutipID,
          remark: this.form.remark,
        }).then((res) => {
          if (res.code >= 200) {
            this.$message.success("批量入库成功！");
            this.dialogFormVisibles = false;
            this.getList1();
          }
        });
      },

      //仓库列表
      getWarehouseLists() {
        getWarehouseList({page: 0}).then((response) => {
          if (response.data) {
            this.WarehouseData = response.data;
          }
        });
      },

      //提交检查项目
      submitfield() {
        let _this = this;
        _this.field = []; //检查项目
        this.fieldList.forEach((item) => {
          _this.field.push({
            form_field: item.id,
            field_value: item.sort,
            is_testok: item.is_testok, //单项检查结果
          });
        });
        this.testrecord.form = this.recordform; //检查表
        this.testrecord.record_data = _this.field; //检查项列表
        this.testrecord.is_testok = this.is_testok; //检查表检查结果
        this.testrecord.wproduct = this.wproduct; //半成品ID
        wproductTest(this.testrecord).then((res) => {
          if (res.code >= 200) {
            this.innerVisible = false;
            this.outerVisible = false;
            this.getList();
            this.getList1();
          }
        });
      },

      //半成品入库
      handlePutin(scope) {
        this.dialogFormVisible = true;
        this.getWarehouseLists(); //仓库
        this.id = scope.row.id; //半成品id
      },

      putin() {
        wproductPutin(this.id, this.form).then((res) => {
          if (res.code >= 200) {
            this.$message.success("入库成功！");
            this.dialogFormVisible = false;
            this.getList1();
          }
        });
      },

      //点击table中的检验
      handleInspection(scope) {
        let that = this;
        //调该物料对应的检查表
        this.wproduct = scope.row.id; //成品ID
        this.listQueryrecordform.material = scope.row.material; //
        this.listQueryrecordform.type = 40;
        this.recordform = null;
        getrecordformList(this.listQueryrecordform).then((response) => {
          if (response.data) {
            this.recordformList = response.data;
            if (response.data.length === 1) {
              that.recordform = response.data[0].id;
              that.formName = response.data[0].name;
              that.submitrecordform();
            } else {
              //弹出列表选择框
              this.outerVisible = true;
            }
          }
        });
      },

      //根据选择的表，渲染检查项目
      submitrecordform() {
        let that = this;
        if (this.recordform != "") {
          testInit({wproduct: that.wproduct, form: that.recordform}).then(
            (response) => {
              if (response.data) {
                that.hasPicture = false;
                that.recordId = response.data.id;
                getTestRecordItem(response.data.id).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.innerVisible = true;
                  });
                });
              }
            }
          );
        } else this.$message.error("请选择检查表！");
      },

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

      //更新检验记录列表
      refreshRecord() {
        let that = this;
        getTestRecord({wproduct: that.wproduct, page: 0}).then((res) => {
          if (res.code == 200) {
            that.recordList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        });
      },

      //检验记录
      checkRecord(scope) {
        let that = this;
        that.wproduct = scope.row.id; //半成品ID
        that.limitedCheckRecord = true;
        getTestRecord({wproduct: scope.row.id, page: 0}).then((res) => {
          if (res.code == 200) {
            that.recordList = res.data;
          } else {
            this.$message.error(res.msg);
          }
        });
      },

      //点击记录里的检验
      handleInspectionRecord(scope) {
        let that = this;
        that.innerVisible = false;
        that.recordId = scope.row.id;
        that.recordform = scope.row.form;
        that.formName = scope.row.form_.name;
        getrffieldList({form: this.recordform, 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;
              }
              getTestRecordItem(scope.row.id).then((res) => {
                let arr = [];
                let fieldList = res.data.record_data;
                for (let i = 0; i < that.fieldList.length; i++) {
                  let obj = that.fieldList[i];
                  obj.is_testok = null;
                  for (let j = 0; j < fieldList.length; j++) {
                    if (that.fieldList[i].field_key === fieldList[j].field_key) {
                      obj.id = parseInt(fieldList[j].id);
                      obj.is_testok = fieldList[j].is_testok;
                      obj.field_value = fieldList[j].field_value;
                    }
                  }
                  arr.push(obj);
                }
                that.fieldList = arr;
                that.$nextTick(() => {
                  that.innerVisible = true;
                });
              });
            }
          }
        );
      },

      delTestRecord(scope) {
        let that = this;
        this.$confirm("确认删除?", "警告", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "error",
        })
          .then(async () => {
            await delTestRecordItem(scope.row.id).then((res) => {
              if (res.code >= 200) {
                that.$message.success("成功");
                that.refreshRecord();
                this.getList();
                this.getList1();
              } else {
                this.$message.error(res.msg);
              }
            });
          })
          .catch((err) => {
            this.$message.error(err);
          });
      },

      //保存检查项目
      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.innerVisible = false;
              that.limitedReview = false;
              that.getList();
              that.getList1();
              that.refreshRecord();
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {
            this.$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.innerVisible = false;
                  that.limitedReview = false;
                  that.limitedCheckRecord = false;
                  this.getList();
                  this.getList1();
                  that.refreshRecord();
                }
              });
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {
            this.$message.error(err);
          });
      },

      //第一次保存提交检查项目
      recordCancel() {
        this.outerVisible = false;
        this.innerVisible = false;
      },
    },
  };
</script>
