<script>
import {
  batchDeleteQuotationTool,
  deleteQuotationTool, saveQuotationTool,
  searchQuotationTool
} from "../../../../../api/quotation/quotationHeader";
import {Decimal} from "decimal.js";
import {searchTool, searchToolHeader} from "../../../../../api/part/toolHeader";

export default {
  name:'toolQuotation',
  props:{
    detail:{
      type:Object,
      request:true,
    },
    height:{
      type:Number,
      default:400,
    },
    totalCost: {
      type:Number,
      default:0,
    }
  },
  data(){
    const validateToolNo = (rule, value, callback) => {
      if (this.saveQuotationToolFlag !== true){
        return;
      }
      if (value === '' || value === null || value === undefined){
        callback(new Error(' '))
        return
      }
      if (value === '*'){
        callback();
        return;
      }
      this.toolHeader.toolNo = value;
      searchTool(this.toolHeader).then(({data})=>{
        if (data.code === 200) {
          if (data.data.length === 1){
            callback()
            return
          }
        }
        this.toolHeader.toolNo = null;
        this.$message.error("工具编码不存在!")
        callback(new Error(' '))
      }).catch((error)=>{
        this.toolHeader.toolNo = null;
        callback(new Error(' '))
      })
    };
    return{
      saveQuotationToolFlag:false,
      quotationToolList:[],
      initQuotationToolLoading:false,
      toolHeaderDialogFlag:false,
      selectionQuotationToolList:[],
      saveQuotationToolLoading:false,
      selectionToolHeaderList:[],
      toolHeaderList:[],
      quotationTool: {
        quotationToolId: undefined,
        site: this.$store.state.user.site,
        toolNo: "",
        toolDescription: "",
        toolQuantity: 1,
        unitCost: 1,
        quotationUnitCost:0,
        expectedServiceLife: 1,
        remark: "",
      },
      // 工具列表筛选对象
      toolHeader:{
        site:this.$store.state.user.site,
        toolNo:undefined,// 编号
        toolDescription:undefined,// 描述
      },
      // 报价工具表单校验
      quotationToolRules: {
        toolNo: [{required: true, message:" ", trigger: 'change'}],
        toolDescription: [{required: true, message: ' ', trigger: ['change','blur']}],
        toolQuantity: [{required: true,pattern:/^[1-9]\d{0,14}(\.\d{1,16})?$|^0(\.\d{1,16})?$/, message: ' ', trigger: ['change','blur']}],
        unitCost: [{required: true,pattern:/^[1-9]\d{0,14}(\.\d{1,16})?$|^0(\.\d{1,16})?$/, message: ' ', trigger: ['change','blur']}],
        expectedServiceLife: [{required: true,pattern:/^[1-9]\d{0,14}(\.\d{1,16})?$|^0(\.\d{1,16})?$/, message: ' ', trigger: ['change','blur']}],
      },
      // 工具列表
      quotationToolColumns: [
        {label: "toolNo", value: "工具编码",},
        {label: "toolDescription", value: "工具描述",},
        {label: "toolQuantity", value: "工具数量",},
        {label: "unitCost", value: "单位成本",},
        {label: "itemNo", value: "序号",},
        {label: "expectedServiceLife", value: "预计使用寿命",},
      ],
      columnList: [
        {
          userId: this.$store.state.user.name,
          functionId: 102003,
          serialNumber: '102003ToolNo',
          tableId: '102003Table6',
          tableName: '工具信息表',
          columnProp: 'toolNo',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '工具编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 102003,
          serialNumber: '102003ToolDescription',
          tableId: '102003Table6',
          tableName: '工具信息表',
          columnProp: 'toolDescription',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '工具描述',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 102003,
          serialNumber: '102003ToolQuantity',
          tableId: '102003Table6',
          tableName: '工具信息表',
          columnProp: 'toolQuantity',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '工具数量',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 100
        },{
          userId: this.$store.state.user.name,
          functionId: 102003,
          serialNumber: '102003UnitCost',
          tableId: '102003Table6',
          tableName: '工具信息表',
          columnProp: 'unitCost',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '单位成本',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 102003,
          serialNumber: '102003ExpectedServiceLife',
          tableId: '102003Table6',
          tableName: '工具信息表',
          columnProp: 'expectedServiceLife',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '预计使用寿命',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 102003,
          serialNumber: '102003QuotationUnitCost',
          tableId: '102003Table6',
          tableName: '工具信息表',
          columnProp: 'quotationUnitCost',
          headerAlign: 'center',
          align: 'right',
          columnLabel: '单位报价成本',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 102003,
          serialNumber: '102003Remark',
          tableId: '102003Table6',
          tableName: '工具信息表',
          columnProp: 'remark',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '备注',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },
      ],
    }
  },
  created() {
    // this.initQuotationToolData();
  },
  methods:{
    getQuotationToolList(){
      // this.initQuotationToolData();
      // 计算成本
      return this.quotationToolList.reduce((total, currentValue) => {
        return total + new Decimal(currentValue.quotationUnitCost).toNumber();
      }, 0);
    },
    initQuotationToolData() {
      let params = {
        quotationDetailId: this.detail.quotationDetailId,
      }
      this.initQuotationToolLoading = true;
      searchQuotationTool(params).then(({data}) => {
        this.initQuotationToolLoading = false;
        if (data && data.code === 200) {
          this.quotationToolList = data.data;
          this.$emit("update:totalCost",this.getQuotationToolList());
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.initQuotationToolLoading = false;
      })
    },
    handleSelectionChangeQuotationToolTable(selection){
      this.selectionQuotationToolList = selection;
    },
    clickEditToolTableBtn(row){
      this.quotationTool = JSON.parse(JSON.stringify(row));
      this.saveQuotationToolFlag= true;
    },
    clickDeleteToolTableBtn(row){
      this.$confirm('确定要删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQuotationTool(row).then(({data})=>{
          if (data.code === 200){
            this.initQuotationToolData();
            this.$message.success(data.msg);
          }else {
            this.$message.error(data.msg);
          }
        })
      })
    },
    deleteSelectionQuotationTool(){
      if (this.selectionQuotationToolList.length === 0) {
        this.$message.warning("请选择要删除的工具记录")
        return;
      }
      this.$confirm('确定要删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchDeleteQuotationTool(this.selectionQuotationToolList).then(({data})=>{
          if (data.code === 200){
            this.initQuotationToolData();
            this.$message.success(data.msg);
          }else {
            this.$message.error(data.msg);
          }
        })
      })
    },
    // 关闭 报价工具 新增弹框
    closeQuotationToolDialog() {
      this.$refs['quotationToolForm'].resetFields();
      this.quotationTool = {
        quotationToolId: undefined,
        site: this.$store.state.user.site,
        toolNo: "",
        toolDescription: "",
        toolQuantity: 1,
        unitCost: 1,
        quotationUnitCost: 0,
        expectedServiceLife: 1,
        remark: "",
      };
      if (this.selectionToolHeaderList.length > 0){
        this.$refs.toolHeaderForm.resetFields();
      }
      this.selectionQuotationToolList = [];
      if (this.$refs.toolHeaderTable) {
        this.$refs.toolHeaderTable.clearSelection();
      }
    },
    openQuotationToolDialog(){
      this.computeToolQuotationUnitCost(this.quotationTool);
    },
    computeToolQuotationUnitCost(row){
      //单位报价成本 = 单位成本 *  工具数量 / 预计使用寿命
      if (!row.expectedServiceLife || row.expectedServiceLife <= 0){
        this.quotationTool.expectedServiceLife = 1;
      }
      if (!row.toolQuantity || row.toolQuantity <= 0){
        this.quotationTool.toolQuantity = 1;
      }
      if (!row.unitCost || row.unitCost < 0){
        this.quotationTool.unitCost = 0;
      }
      if (!row.expectedServiceLife || !row.toolQuantity || !row.unitCost){
        row.quotationUnitCost = 0;
        return
      }
      row.quotationUnitCost = new Decimal(new Decimal(row.unitCost).mul(new Decimal(row.toolQuantity)).div(new Decimal(row.expectedServiceLife)).toFixed(4,Decimal.ROUND_HALF_UP)).toSignificantDigits().toNumber();
    },
    saveQuotationTool() {
      this.$refs['quotationToolForm'].validate((validate, object) => {
        if (validate) {
          this.saveQuotationToolLoading = true;
          this.quotationTool.quotationDetailId = this.detail.quotationDetailId;
          this.insertQuotationToolData();
        } else {
          this.rulesValidateLabel(object, this.quotationToolColumns);// 校验提示
        }
      })
    },
    insertQuotationToolData(){
      saveQuotationTool(this.quotationTool).then(({data}) => {
        this.saveQuotationToolLoading = false;
        if (data.code === 200) {
          this.initQuotationToolData();
          this.$message.success(data.msg);
          this.saveQuotationToolFlag = false;// 关闭弹框
        } else {
          this.$message.error(data.msg);
        }
      }).catch((error)=>{
        this.saveQuotationToolLoading = false;
      })
    },
    // 打开 工具信息弹框
    openToolHeaderDialog(){
      if (this.selectionToolHeaderList.length > 0) {
        this.$refs.quotationToolForm.resetFields();
      }
    },
    initToolHeader(){
      searchToolHeader(this.toolHeader).then(({data})=>{
        if (data.code === 200) {
          this.toolHeaderList = data.data;
          this.toolHeaderList = this.toolHeaderList.map(item =>{
            let utilObj = {
              toolNo:item.toolId,
              toolDescription:item.toolDescription,
              unitCost:item.standardCost,
            }
            return utilObj;
          })
        }
      })
    },
    handleSelectionChangeToolHeaderTable(selection){
      this.selectionToolHeaderList = selection;
    },
    dblclickToolHeader(row){
      row = JSON.parse(JSON.stringify(row));
      this.quotationTool.toolNo = row.toolNo;
      this.quotationTool.toolDescription = row.toolDescription;
      this.quotationTool.unitCost = row.unitCost ? row.unitCost : 0;
      this.computeToolQuotationUnitCost(this.quotationTool)
      this.toolHeaderDialogFlag= false;
    },
    // 校验处理
    rulesValidateLabel(objects, labels) {
      for (let filed in objects) {
        for (let i = 0; i < labels.length; i++) {
          let quotationToolColumn = labels[i];
          if (quotationToolColumn.label === filed) {
            this.$message.warning(quotationToolColumn.value+"为空或填写不正确");
            return
          }
        }
      }
    },
  },
}
</script>

<template>
<div>
  <div>
    <el-button type="primary" @click="saveQuotationToolFlag = true">新 增</el-button>
    <el-button type="primary" @click="deleteSelectionQuotationTool">删 除</el-button>
  </div>
  <el-table style="margin-top: 5px" ref="quotationToolTable"
            v-loading="initQuotationToolLoading"
            element-loading-text = "数据正在加载中"
            @selection-change="handleSelectionChangeQuotationToolTable"
            :data="quotationToolList" :height="height" stripe border>
    <el-table-column
      type="selection"
      align="center"
      width="55">
    </el-table-column>
    <el-table-column label="操作" width="120" align="center" >
      <template slot-scope="{row,$index}">
        <el-link style="cursor: pointer" @click="clickEditToolTableBtn(row)">编辑</el-link>
<!--        <el-link style="cursor: pointer" @click="clickDeleteToolTableBtn(row)">删除</el-link>-->
      </template>
    </el-table-column>
    <el-table-column
      v-for="(item,index) in columnList" :key="index"
      :sortable="item.columnSortable"
      :prop="item.columnProp"
      :header-align="item.headerAlign"
      :show-overflow-tooltip="item.showOverflowTooltip"
      :align="item.align"
      :fixed="item.fixed===''?false:item.fixed"
      :min-width="item.columnWidth"
      :label="item.columnLabel">
      <template slot-scope="scope" >
        <span v-if="!item.columnHidden"> {{ scope.row[item.columnProp]}}</span>
        <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog title="报价工具" v-drag
             @close="closeQuotationToolDialog"
             @open="openQuotationToolDialog"
             :visible.sync="saveQuotationToolFlag" width="40%"
             :close-on-click-modal="false"
             top="15vh" append-to-body>
    <el-form :rules="quotationToolRules" ref="quotationToolForm" :model="quotationTool" label-position="top"
             style="height: 260px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="工具编码" prop="toolNo">
            <span slot="label" @click="toolHeaderDialogFlag = true" style="cursor: pointer"><a>工具编码</a></span>
            <el-input v-model="quotationTool.toolNo" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="2">
          <el-form-item label="工具描述" prop="toolDescription">
            <el-input v-model="quotationTool.toolDescription" :disabled="quotationTool.toolNo !== '*'" clearable/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="工具数量" prop="toolQuantity">
            <el-input-number style="margin-top: -5px;width: 100%;" v-model="quotationTool.toolQuantity" :controls="false" :min="1" @input="computeToolQuotationUnitCost(quotationTool)"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="2">
          <el-form-item label="预计使用寿命" prop="expectedServiceLife">
            <el-input-number style="margin-top: -5px;width: 100%" v-model="quotationTool.expectedServiceLife" :controls="false" :min="1" @input="computeToolQuotationUnitCost(quotationTool)"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单位成本" prop="unitCost">
            <el-input-number style="margin-top: -5px;width: 100%" v-model="quotationTool.unitCost" :disabled="quotationTool.toolNo !== '*'" :controls="false" :min="1" @input="computeToolQuotationUnitCost(quotationTool)"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="2">
          <el-form-item label="单位报价成本" prop="unitCost">
            <el-input-number disabled style="margin-top: -5px;width: 100%" v-model="quotationTool.quotationUnitCost" :controls="false" :min="1"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark" style="height: 90px">
        <el-input v-model="quotationTool.remark" resize="none" type="textarea" :autosize="{minRows: 3, maxRows: 3}" style="width: 93%"/>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" style="margin-top: 5px">
        <el-button type="primary" :loading="saveQuotationToolLoading" @click="saveQuotationTool">确 定</el-button>
        <el-button @click="saveQuotationToolFlag= false">取 消</el-button>
      </span>
  </el-dialog>

  <!--tool列表-->
  <el-dialog v-drag title="工具信息"
             @open="openToolHeaderDialog"
             width="40%" top="15vh" append-to-body
             :close-on-click-modal="false"
             :visible.sync="toolHeaderDialogFlag">
    <!--搜索条件-->
    <el-form :model="toolHeader" ref="toolHeaderForm" :inline="true" label-position="top">
      <el-form-item label="工具编号" prop="toolNo">
        <el-input v-model="toolHeader.toolNo" clearable/>
      </el-form-item>
      <el-form-item label="工具描述" prop="toolDescription">
        <el-input v-model="toolHeader.toolDescription" clearable/>
      </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" @click="initToolHeader">搜 索</el-button>
      </el-form-item>
    </el-form>
    <!--筛选的数据-->
    <el-table :data="toolHeaderList" ref="toolHeaderTable" :style="{marginTop:'10px'}"
              height="300px" stripe border @selection-change="handleSelectionChangeToolHeaderTable"
              @row-dblclick="dblclickToolHeader">
      <el-table-column label="工具编号" prop="toolNo"/>
      <el-table-column label="工具描述" prop="toolDescription"/>
    </el-table>
  </el-dialog>
</div>
</template>

<style scoped>
.el-input-number /deep/ .el-input__inner{
  text-align: right;
  padding-right: 5px !important;
}
</style>
