<template>
  <basic-container>
    <avue-crud :option="option"
               v-model:search="search"
               v-model:page="page"
               v-model="form"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
        <!-- <el-button type="danger"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.productBatch_delete"
                   @click="handleDelete">删 除
        </el-button> -->
        <!-- <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   @click="handleExport">导 出
        </el-button> -->
      </template>
      
      <template #menu="{row,index,size}">
      <el-button type="primary"
                 text
                 :size="size"
                 icon="el-icon-edit"
                v-if="permission.productBatch_edit"
                 @click="rowEdit(row,index)">编辑</el-button>
        <el-button type="primary"
                 text
                :size="size"
                icon="el-icon-edit"
                v-if="permission.productBatch_change"
                @click="rowChange(row,index)">变更</el-button>
      </template>
      <template #details-form>
        <avue-crud :option="optionSub" ref="detailCrud"
                  :data="form.details">
                  <template #qrCode-form="{row}">
                    <el-input v-model="row.qrCode"
                              :disabled="row.id"></el-input>
                  </template>
                  <template #menu="{row,index,size}">
                    <el-popconfirm title="确认删除入库产品数据么？" @confirm="delDetail(index)">
                      <template #reference>
                        <el-button  v-if="index>0"
                                  :size="size"
                                  type="primary"
                                  text>删除</el-button>
                      </template>
                    </el-popconfirm>
                  </template>
                  <!-- <template slot-scope="{row,index}" slot="menu">
                    <el-button v-if="row.$cellEdit"
                              text
                              icon="el-icon-cancel"
                              type="primary"
                              @click="rowDelSub(index)">删除</el-button>
                  </template>
                  <template slot-scope="{row}" slot="tradeTotalPriceForm">
                    <span>{{(row.tradeUnitPrice * row.tradeNum)? (row.tradeUnitPrice * row.tradeNum).toFixed(2):0 }}</span>
                  </template> -->

                  <!-- <template slot-scope="{row,index}" slot="productIdForm">
                    <el-button v-if="row.$cellEdit"
                              text
                              icon="el-icon-cancel"
                              type="primary"
                              @click="rowDelSub(index)">删除</el-button>
                  </template> -->
        </avue-crud>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/productBatch/productBatch";
  import {getDetail as getModelDetail } from "@/api/productModel/productModel";
  import option from "@/option/productBatch/productBatch";
  import optionSub from "@/option/productBatch/product.js";
  import {mapGetters} from "vuex";
  import {exportBlob} from "@/api/common";
  import {getToken} from '@/utils/auth';
  import {downloadXls} from "@/utils/util";
  import {dateNow} from "@/utils/date";
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';

  export default {
    data() {
      return {
        form: {},
        query: {},
        search: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: option,
        data: [],
        optionSub: optionSub,
        isChange:false,
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.productBatch_add, false),
          viewBtn: this.validData(this.permission.productBatch_view, false),
          delBtn: this.validData(this.permission.productBatch_delete, false),
          editBtn: this.validData(this.permission.productBatch_edit, false),
          changeBtn: this.validData(this.permission.productBatch_change, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    watch: {
      // 'form.factoryId'(newValue, oldValue) {
      //   this.$nextTick(() => {
      //     this.form.clientId='';
      //     this.form.productModelId='';
      //   });
      // }

      'form.productModelId'(newValue, oldValue) {
        if(newValue){
          this.$nextTick(() => {
            getModelDetail(newValue).then(res => {
              this.optionSub.column.waterCooling.hide= !(","+res.data.data.inStockFormItem+",").includes(",water_cooling,")
              this.optionSub.column.airtight.hide= !(","+res.data.data.inStockFormItem+",").includes(",airtight,")
              this.optionSub.column.coldQrCode.hide= !(","+res.data.data.inStockFormItem+",").includes(",cold_qr_code,")
            });
          });
        }
      }

    },
    created () {
      let that = this;
      this.option.column.productModelId.change= function (column) {
          // 函数体
          if(column.value){
            if(column.item){
              console.log(column.item.inStockNum)
              this.$nextTick(() => {
                var details = [];
                for(let i=0;i<column.item.inStockNum;i++){
                  details.push({"$cellEdit":true})
                }
                that.form.details = details
              });
            }
            // if(!this.form.details){
            //   this.form.details = [{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true}]
            // }
          }
      };
    },
    methods: {
      rowSave(row, done, loading) {
        this.$refs.detailCrud.$refs.cellForm.validate((valid) => {
          if (valid) {
            add(row).then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              done();
            }, error => {
              loading();
              window.console.log(error);
           });
          } else {
            loading();
            return false;
          }
        })
      },
      rowUpdate(row, index, done, loading) {
        this.$refs.detailCrud.$refs.cellForm.validate((valid) => {
          if (valid) {
            debugger
            update(this.isChange,row).then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              done();
            }, error => {
              loading();
              console.log(error);
            });
          } else {
            loading();
            return false;
          }
        })
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleExport() {
        let downloadUrl = `/pl-productBatch/productBatch/export-productBatch?${this.website.tokenHeader}=${getToken()}`;
        const {
            batchNo,
            productName,
            productModel,
        } = this.query;
        let values = {
            batchNo_: batchNo,
            productName_: productName,
            productModel_: productModel,
        };
        this.$confirm("是否导出数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          NProgress.start();
          exportBlob(downloadUrl, values).then(res => {
            downloadXls(res.data, `产品入库批次表${dateNow()}.xlsx`);
            NProgress.done();
          })
        });
      },
      rowChange(row,index){
        this.isChange = true;
        this.$refs.crud.rowEdit(row,index)
      },
      rowEdit(row,index){
        this.isChange = false;
        this.$refs.crud.rowEdit(row,index)
      },
      beforeOpen(done, type) {
        this.optionSub.menu = false;
        
        this.option.column.productModelId.disabled=false;
        this.option.column.clientId.disabled=false;
        this.option.column.factoryId.disabled=false;
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            if(type == "edit"){
              this.option.column.productModelId.disabled=true;
              this.option.column.clientId.disabled=true;
              this.option.column.factoryId.disabled=true;
              this.form.details.forEach(item =>{
                item["$cellEdit"] = true
              })
            }
              this.optionSub.column.waterCooling.hide= !(","+res.data.data.inStockFormItem+",").includes(",water_cooling,")
              this.optionSub.column.airtight.hide= !(","+res.data.data.inStockFormItem+",").includes(",airtight,")
              this.optionSub.column.coldQrCode.hide= !(","+res.data.data.inStockFormItem+",").includes(",cold_qr_code,")
              
              this.option.column.orderNo.disabled=this.isChange;
              this.optionSub.column.newQrCode.hide=!this.isChange
              this.optionSub.column.waterCooling.disabled=this.isChange
              this.optionSub.column.airtight.disabled=this.isChange
              this.optionSub.column.coldQrCode.disabled=this.isChange
          });
        }
        if (["add"].includes(type)) {
          this.optionSub.menu = true;
          if(!this.form.details){
            this.form.details = [{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true},{"$cellEdit":true}]
            
          }
        }
        done();
      },
      beforeClose (done, type) {
        this.isChange = false;
      },
      delDetail(index){
			  this.form.details.splice(index,1)
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;

        const {
          batchNo,
          productName,
          clientId,
          factoryId,
          productModelId,
          qrCode
        } = this.query;

        let values = {
          batchNo_like: batchNo,
          productName_like: productName,
          productModelId: productModelId,
          clientId: clientId,
          factoryId: factoryId,
          qrCode:qrCode,
        };

        getList(page.currentPage, page.pageSize, values).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
          this.$nextTick(() => {
            //放在数据加载完后执行
            this.$refs.crud.dicInit('cascader');
          })
        });
      }
    }
  };
</script>

<style>
</style>
