<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="factoryNo">
        <el-input
          v-model="queryParams.factoryNo"
          placeholder="请输入编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="factoryName">
        <el-input
          v-model="queryParams.factoryName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="['factory:factory: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="['factory:factory: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="['factory:factory: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="['factory:factory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table width="100%"  v-loading="loading" :data="factoryList" :row-class-name="rowFactoryIndex" @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="factoryId" v-if="false"/>
      <el-table-column label="编码" width="100" align="center" prop="factoryNo" />
      <el-table-column label="名称" width="100" align="center" prop="factoryName" />
      <el-table-column label="人工成本占比(%)" width="150" align="center" prop="factoryRgRatio" />
      <el-table-column label="五金费用占比(%)" width="150" align="center" prop="factoryWjRatio" />
      <el-table-column label="辅料费用占比(%)" width="150" align="center" prop="factoryFlRatio" />
      <el-table-column label="电费占比(%)" width="150" align="center" prop="factoryDfRatio" />
      <el-table-column label="天然气费用占比(%)" width="150" align="center" prop="factoryTrqRatio" />
      <el-table-column label="运输费用占比(%)" width="150" align="center" prop="factoryYsRatio" />
      <el-table-column label="总占比(%)" width="150" align="center" prop="factoryTotalRatio" />
      <el-table-column label="盘具费用占比(%)" width="150" align="center" prop="factoryPjRatio" />
      <el-table-column fixed="right"  label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['factory:factory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['factory:factory: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="800px" 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="factoryNo" label-width="150px">
              <el-input v-model="form.factoryNo" placeholder="请输入编码" :disabled="isDis"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="factoryName" label-width="150px">
              <el-input v-model="form.factoryName" placeholder="请输入名称" :disabled="isDis" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="人工成本占比(%)" prop="factoryRgRatio" label-width="150px">
              <el-input v-model="form.factoryRgRatio" placeholder="请输入人工成本占比" @input="wat()"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="五金费用占比(%)" prop="factoryWjRatio" label-width="150px">
              <el-input v-model="form.factoryWjRatio" placeholder="请输入五金费用占比"  @input="wat()"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="辅料费用占比(%)" prop="factoryFlRatio" label-width="150px">
              <el-input v-model="form.factoryFlRatio" placeholder="请输入辅料费用占比"  @input="wat()"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电费占比(%)" prop="factoryDfRatio" label-width="150px">
              <el-input v-model="form.factoryDfRatio" placeholder="请输入电费占比"  @input="wat()"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="天然气费用占比(%)" prop="factoryTrqRatio" label-width="150px">
              <el-input v-model="form.factoryTrqRatio" placeholder="请输入天然气费用占比"  @input="wat()"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运输费用占比(%)" prop="factoryYsRatio" label-width="150px">
              <el-input v-model="form.factoryYsRatio" placeholder="请输入运输费用占比"  @input="wat()"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="盘具费用占比(%)" prop="factoryPjRatio" label-width="150px">
              <el-input v-model="form.factoryPjRatio" placeholder="请输入盘具费用占比" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总占比(%)" prop="factoryYsRatio" label-width="150px">
              <el-input v-model="form.factoryTotalRatio" :disabled="true"/>
            </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="handleAddCMaterialType">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteCMaterialType">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="cmaterialTypeList" width="100%" :row-class-name="rowCMaterialTypeIndex" @selection-change="handleCMaterialTypeSelectionChange" ref="cMaterialType">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" width="50" align="center" prop="index"/>
          <el-table-column label="编码" prop="typeNo">
            <!--<template slot-scope="scope">
              <el-input v-model="scope.row.typeNo" placeholder="请输入编码" />
            </template>-->
            <template slot-scope="scope">
                <el-select v-model="scope.row.typeNo" placeholder="请选择" @change="selectTypeChange(scope.row)">
                  <el-option
                    v-for="item in cTypeList"
                    :key="item.typeNo"
                    :label="item.typeNo + '-' + item.typeName"
                    :value="item.typeNo"
                  />
                </el-select>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="typeName"></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: 0px; /* 向上偏移5像素 */
    margin-bottom: 0px; /* 向下偏移5像素 */
  }
</style>
<script>
import { listFactory, getFactory, delFactory, addFactory, updateFactory,listMaterialType } from "@/api/factory/factory";
import { numAdd,numSub,numMulti,numDiv } from "@/utils/operation";

export default {
  name: "Factory",
  dicts: ['material_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCMaterialType: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车间管理表格数据
      factoryList: [],
      // 物料类别表格数据
      cmaterialTypeList: [],
      cTypeList: [],
      cTypeMap: {},

      //是否可编辑
      isDis: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        factoryNo: null,
        factoryName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        factoryRgRatio: [
          {
            pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,3})?$/,
            message: "格式错误",
            trigger: "blur"
          }
        ],
        factoryWjRatio: [
          {
            pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,3})?$/,
            message: "格式错误",
            trigger: "blur"
          }
        ],
        factoryFlRatio: [
          {
            pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,3})?$/,
            message: "格式错误",
            trigger: "blur"
          }
        ],
        factoryDfRatio: [
          {
            pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,3})?$/,
            message: "格式错误",
            trigger: "blur"
          }
        ],
        factoryTrqRatio: [
          {
            pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,3})?$/,
            message: "格式错误",
            trigger: "blur"
          }
        ],
        factoryYsRatio: [
          {
            pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,3})?$/,
            message: "格式错误",
            trigger: "blur"
          }
        ],
        factoryPjRatio: [
          {
            pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,3})?$/,
            message: "格式错误",
            trigger: "blur"
          }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询车间管理列表 */
    getList() {
      this.loading = true;
      listFactory(this.queryParams).then(response => {
        this.factoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    //物料类别列表
    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 = {
        factoryId: null,
        factoryNo: null,
        factoryName: null,
        factoryRgRatio: null,
        factoryWjRatio: null,
        factoryFlRatio: null,
        factoryDfRatio: null,
        factoryTrqRatio: null,
        factoryYsRatio: null,
        factoryPjRatio: null,
        factoryTotalRatio: null
      };
      this.cmaterialTypeList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.factoryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车间管理";
      this.isDis = false;
      this.getMaterialType();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const factoryId = row.factoryId || this.ids
      getFactory(factoryId).then(response => {
        this.form = response.data;
        this.cmaterialTypeList = response.data.cmaterialTypeList;
        this.open = true;
        this.title = "修改车间管理";
        this.isDis = true;
        this.getMaterialType();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.cmaterialTypeList = this.cmaterialTypeList;

          console.log(this.form)
          if (this.form.factoryId != null) {
            updateFactory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFactory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const factoryIds = row.factoryId || this.ids;
      this.$modal.confirm('是否确认删除车间管理编号为"' + factoryIds + '"的数据项？').then(function() {
        return delFactory(factoryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 物料类别序号 */
    rowCMaterialTypeIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 物料类别添加按钮操作 */
    handleAddCMaterialType() {
      let obj = {};
      obj.typeNo = "";
      obj.typeName = "";
      this.cmaterialTypeList.push(obj);
    },
    /** 物料类别删除按钮操作 */
    handleDeleteCMaterialType() {
      if (this.checkedCMaterialType.length == 0) {
        this.$modal.msgError("请先选择要删除的物料类别数据");
      } else {
        debugger
        const cmaterialTypeList = this.cmaterialTypeList;
        const checkedCMaterialType = this.checkedCMaterialType;
        this.cmaterialTypeList = cmaterialTypeList.filter(function(item) {
          return checkedCMaterialType.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleCMaterialTypeSelectionChange(selection) {
      this.checkedCMaterialType = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('factory/factory/export', {
        ...this.queryParams
      }, `factory_${new Date().getTime()}.xlsx`)
    },
    /*更改物料类型事件*/
    selectTypeChange(row){
      console.log(row.typeNo)
      row.typeName = this.cTypeMap[row.typeNo];
    },
    //计算占比总和
    wat(){
      var RgRatio = this.form.factoryRgRatio?parseFloat(this.form.factoryRgRatio):0;
      var WjRatio = this.form.factoryWjRatio?parseFloat(this.form.factoryWjRatio):0;
      var FlRatio = this.form.factoryFlRatio?parseFloat(this.form.factoryFlRatio):0;
      var DfRatio = this.form.factoryDfRatio?parseFloat(this.form.factoryDfRatio):0;
      var TrqRatio = this.form.factoryTrqRatio?parseFloat(this.form.factoryTrqRatio):0;
      var YsRatio = this.form.factoryYsRatio?parseFloat(this.form.factoryYsRatio):0;

      this.form.factoryTotalRatio = (RgRatio+WjRatio+FlRatio+DfRatio+TrqRatio+YsRatio).toFixed(3)
    },
    /** 序号 */
    rowFactoryIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    }
  }
};
</script>
