<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="型号" prop="materialXingh">
        <el-input
          v-model="queryParams.materialXingh"
          placeholder="请输入型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格" prop="materialGuig">
        <el-input
          v-model="queryParams.materialGuig"
          placeholder="请输入规格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电压" prop="materialDiany">
        <el-input
          v-model="queryParams.materialDiany"
          placeholder="请输入电压"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="materialState">
        <el-select v-model="queryParams.materialState" placeholder="物料状态" clearable>
          <el-option
            v-for="dict in dict.type.material_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['material:material:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['material:material:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['material:material:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['material:material:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh-right"
          size="mini"
          @click="handleSynchronize"
          v-hasPermi="['material:material:synchronizeMaterialData']"
        >同步物料材料用量</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialList" :row-class-name="rowCMaterialIndex" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="index" width="80"/>
      <el-table-column label="id" align="center" prop="materialId" v-if="false"/>
      <el-table-column label="类型" align="center" prop="typeName" />
      <el-table-column label="型号" align="center" prop="materialXingh" />
      <el-table-column label="规格" align="center" prop="materialGuig" />
      <el-table-column label="电压" align="center" prop="materialDiany" />
      <el-table-column label="单位" align="center" prop="materialDw" />
      <el-table-column prop="materialState" label="状态" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_state" :value="scope.row.materialState"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['material:material:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['material:material:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="类别" prop="materialTypeId">
              <el-select v-model="form.materialTypeId" placeholder="请选择">
                <el-option
                  v-for="item in cTypeList"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="materialState" label="停用状态" label-width="100px">
              <el-radio-group v-model="form.materialState">
                <el-radio
                  v-for="dict in dict.type.material_state"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="型号" prop="materialXingh">
              <el-input v-model="form.materialXingh" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="materialGuig">
              <el-input v-model="form.materialGuig" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电压" prop="materialDiany">
              <el-input v-model="form.materialDiany" placeholder="请输入电压" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="materialDw">
              <el-input v-model="form.materialDw" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>

<!--
        <el-divider content-position="center">物料成本信息</el-divider>
-->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddCMaterialCost">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteCMaterialCost">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="cMaterialCostList" height="350" width="100%" :row-class-name="rowCMaterialCostIndex" @selection-change="handleCMaterialCostSelectionChange" ref="cMaterialCost" :show-summary="showSum" :summary-method="tableHJ">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="关联用料" width="300" prop="costClId">
            <template slot-scope="scope">
<!--
              <el-input v-model="scope.row.costClId" placeholder="请输入关联用料id" />
-->
              <el-select v-model="scope.row.costClId" placeholder="请选择" @change="selectClChange(scope.row)">
                <el-option
                  v-for="item in cmaterials"
                  :key="item.materialId"
                  :label="item.materialNo + '-' +item.materialName"
                  :value="item.materialNo"
                />
              </el-select>
            </template>
          </el-table-column>
<!--
          <el-table-column label="关联用料" prop="materialName"></el-table-column>
-->
          <el-table-column label="用量" prop="costClQty">
            <template slot-scope="scope">
              <el-form-item class="offset" :prop="'cmaterialCostList.' + scope.$index + '.costClQty'" :rules="rules.costClQty" label-width="0" >
                <el-input v-model="scope.row.costClQty" placeholder="请输入用量" @input="wat(scope.$index)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="用量2" prop="costClQty2">
            <template slot-scope="scope">
              <el-form-item class="offset" :prop="'cmaterialCostList.' + scope.$index + '.costClQty2'" :rules="rules.costClQty2" label-width="0" >
                <el-input v-model="scope.row.costClQty2" placeholder="请输入用量2" @input="wat(scope.$index)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="materialPrice"></el-table-column>
          <el-table-column label="总价" prop="materialPriceTotal"></el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
  /* 根据需求设置位置上下偏移 */
  .offset {
    margin-top: 15px; /* 向上偏移5像素 */
    margin-bottom: 15px; /* 向下偏移5像素 */
  }
</style>
<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, listClMaterial, listMaterialType, synchronizeUpdate } from "@/api/material/material";
import log from "../../monitor/job/log";
import { numAdd,numSub,numMulti,numDiv } from "@/utils/operation";

export default {
  name: "Material",
  dicts: ['material_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCMaterialCost: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //列表总计
      showSum: true,
      // 物料管理表格数据
      materialList: [],
      // 物料成本表格数据
      cMaterialCostList: [],
      //物料类型选项
      cTypeList: [],
      //材料选项
      cmaterials: [],
      cmaterialsmap: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialXingh: null,
        materialGuig: null,
        materialDiany: null,
        materialState: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialXingh: [
          { required: true, message: "型号不能为空", trigger: "blur" }
        ],
        materialGuig: [
          { required: true, message: "规格不能为空", trigger: "blur" }
        ],
        materialTypeId: [
          { required: true, message: "类别不能为空", trigger: "blur" }
        ],
        costClQty: [
          { pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,4})?$/, message: '格式有误',trigger: "blur"}
        ],
        costClQty2: [
          { pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,4})?$/, message: '格式有误',trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  computed:{

  },

  methods: {
    /** 查询物料管理列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    //材料选项
    getClMaterials(){
      listClMaterial(this.queryParams).then(response => {
        this.cmaterials = response.cmaterials;

        let obj = {};
        this.cmaterials.forEach(item => {
          let key = item.materialNo;
          obj[key] = item.materialPrice;
        })
        this.cmaterialsmap = obj;
      });
    },

    //物料类别列表
    getMaterialType(){
      this.queryParams.typeState='0';//筛选正常的类别
      listMaterialType(this.queryParams).then(response => {
        this.cTypeList = response.cTypeList;
/*
        let obj = {};
        this.cTypeList.forEach(item => {
          let key = item.typeNo;
          obj[key] = item.typeName;
        })
        this.cTypeMap = obj;*/
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: null,
        materialXingh: null,
        materialGuig: null,
        materialDiany: null,
        materialDw: null,
        materialState: '0'
      };
      this.cMaterialCostList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料管理";
      this.materialState = '0';
      this.getClMaterials();
      this.getMaterialType();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materialId = row.materialId || this.ids
      getMaterial(materialId).then(response => {
        this.form = response.data;
        this.cMaterialCostList = response.data.cmaterialCostList;
        console.log(response.data.cmaterialCostList)
        this.open = true;
        this.title = "修改物料管理";
        this.getClMaterials();
        this.getMaterialType();
        this.sumPriceTotal()
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.cmaterialCostList = this.cMaterialCostList;
          console.log(this.form.cMaterialCostList)
          if (this.form.materialId != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialIds = row.materialId || this.ids;
      this.$modal.confirm('是否确认删除物料管理编号为"' + materialIds + '"的数据项？').then(function() {
        return delMaterial(materialIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 物料成本序号 */
    rowCMaterialCostIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 物料成本添加按钮操作 */
    handleAddCMaterialCost() {
      let obj = {};
      obj.costClId = "";
      obj.costClQty = "";
      obj.costClQty2 = "";
      obj.materialPrice = "";
      this.cMaterialCostList.push(obj);
    },
    /** 物料成本删除按钮操作 */
    handleDeleteCMaterialCost() {
      if (this.checkedCMaterialCost.length == 0) {
        this.$modal.msgError("请先选择要删除的物料成本数据");
      } else {
        const cMaterialCostList = this.cMaterialCostList;
        const checkedCMaterialCost = this.checkedCMaterialCost;
        this.cMaterialCostList = cMaterialCostList.filter(function(item) {
          return checkedCMaterialCost.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleCMaterialCostSelectionChange(selection) {
      this.checkedCMaterialCost = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('material/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    },
    /** 序号 */
    rowCMaterialIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    //页面加载计算每行总价
    sumPriceTotal(){
      this.cMaterialCostList.forEach((row, index) => {
        this.wat(index)
      })
    },

    //计算每行总价
    wat(index){
      this.showSum = false;
      let tmpObj = this.cMaterialCostList[index];
      var costClQty = tmpObj.costClQty?tmpObj.costClQty:0;
      var costClQty2 = tmpObj.costClQty2?tmpObj.costClQty2:0;
      var qty = numAdd(costClQty,costClQty2);
      var materialPrice = tmpObj.materialPrice?tmpObj.materialPrice:0;;
      this.$vue.set(tmpObj, 'materialPriceTotal', numMulti(qty,materialPrice));
      this.$nextTick()
        .then(() => {
          this.showSum = true;
        })
    },

    /** 产品明细金额合计 暂时不用*/
    tableHJ(param){
       const { columns, data } = param;
       const sums = [];
       columns.forEach((column, index) => {
         if (index === 2) {
           sums[index] = '合计';
           return;
         }

         const values = data.map(item => Number(item[column.property]));
         // 对数量、合同总价进行总计核算。
         if (column.property === 'materialPriceTotal') {
           if (!values.every(value => isNaN(value))) {
             sums[index] = values.reduce((prev, curr) => {
               const value = Number(curr);
               if (!isNaN(value)) {
                 return prev + curr;
               }else {
                 return prev;
               }
             }, 0);
             sums[index] = Math.round(sums[index]*100)/100;
           } else {
             sums[index] = 'NaN'
           }
         }
       });
       return sums;
    },

    /*更改用料事件*/
    selectClChange(row){
      row.materialPrice = this.cmaterialsmap[row.costClId];
      this.sumPriceTotal()
    },

    /*同步物料材料用量*/
    handleSynchronize(){
      this.$modal.confirm('是否确认同步更新？').then(function() {
        return synchronizeUpdate();
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("更新成功");
      }).catch(() => {});
    }
  }
};
</script>
