<template>
  <div class="app-container">
    <el-card>
      <div>
        <el-button v-if="checkPermission(['material_create'])" type="primary" icon="el-icon-plus" @click="handleCreate">
          新增物料
        </el-button>
        <el-input
          v-model="listQuery.search"
          placeholder="物料名称/物料编号"
          style="width: 300px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >搜索
        </el-button>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-refresh-left"
          @click="resetFilter"
        >重置
        </el-button>
      </div>
    </el-card>
    <el-card style="margin-top: 2px">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <!--<el-tab-pane label="成品" name="1"></el-tab-pane>
        <el-tab-pane label="半成品" name="2"></el-tab-pane>-->
        <el-tab-pane label="主要原料" name="3"></el-tab-pane>
        <el-tab-pane label="辅助材料" name="4"></el-tab-pane>
        <el-tab-pane label="加工工具" name="5"></el-tab-pane>
        <el-tab-pane label="辅助工装" name="6"></el-tab-pane>
      </el-tabs>
      <el-table
        v-loading="listLoading"
        :data="materialList.results"
        border
        fit
        stripe
        highlight-current-row
        height="100"
        v-el-height-adaptive-table="{bottomOffset: 50}"
      >
        <el-table-column type="index" width="50"/>
        <el-table-column label="物料编号">
          <template slot-scope="scope">
            {{ scope.row.number }}
          </template>
        </el-table-column>
        <el-table-column label="物料类别">
          <template slot-scope="scope"> {{options_[scope.row.type]}}</template>
        </el-table-column>
        <el-table-column label="物料名称">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="规格型号">
          <template slot-scope="scope">{{ scope.row.specification }}</template>
        </el-table-column>
        <!--<el-table-column label="单片玻璃数量" v-if="materialList.results[0].type==1">
          <template slot-scope="scope">{{ scope.row.piece_count }}</template>
        </el-table-column>-->
        <el-table-column label="计量单位">
          <template slot-scope="scope">{{ scope.row.unit }}</template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">{{ scope.row.create_time }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="220px"
        >
          <template slot-scope="scope">
            <el-link
              v-if="checkPermission(['material_update'])&&scope.row.type!=5&&scope.row.type!=6"
              type="primary"
              @click="handlebind(scope)"
            >检查表
            </el-link>
            <el-link
              v-if="checkPermission(['material_update'])"
              type="primary"
              @click="handleEdit(scope)"
            >编辑
            </el-link>
            <el-link
              type="primary"
              @click="handledetail(scope)"
            >详情
            </el-link>
            <el-link
              v-if="checkPermission(['material_delete'])"
              type="danger"
              @click="handleDelete(scope)"
            >删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="materialList.count > 0"
        :total="materialList.count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :title="dialogType === 'edit' ? '编辑物料' : '新增物料'"
    >
      <el-form
        ref="Form"
        :model="material"
        label-width="100px"
        label-position="right"
        :rules="rule1"
      >
        <el-form-item label="物料名称" prop="name">
          <el-input v-model="material.name" placeholder="物料名称"/>
        </el-form-item>
        <el-form-item label="物料编号" prop="number">
          <el-input v-model="material.number" placeholder="物料编号"/>
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="material.specification" placeholder="规格型号"/>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-select style="width: 100%" v-model="material.unit" placeholder="请选择">
            <el-option
              v-for="item in unitoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料类别">
          <el-select style="width: 100%" v-model="material.type" placeholder="请选择物料类别">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单片玻璃数量" v-if="material.type==1">
          <el-input v-model="material.piece_count" placeholder="单片玻璃数量"/>
        </el-form-item>
        <el-form-item label="安全库存数">
          <el-input-number style="width: 100%;" v-model="material.count_safe" :step="1" :min="0" step-strictly placeholder="安全库存数"></el-input-number>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number style="width: 100%;" v-model="material.sort_str" :step="1" :min="0" step-strictly placeholder="排序"></el-input-number>
        </el-form-item>
        <el-form-item label="详情文件">
          <el-upload
            ref="upload"
            :action="upUrl"
            :on-preview="handlePreview"
            :on-success="handleUpSuccess"
            :on-remove="handleRemove"
            :headers="upHeaders"
            :file-list="fileList"
            :limit="1"
            accept=".pdf"
          >
            <el-button size="small" type="primary">上传文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm('Form')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    getMaterialList,
    getMaterial,
    createMaterial,
    updateMaterial,
    deleteMaterial,
    getProcessList
  } from "@/api/mtm";
  import checkPermission from "@/utils/permission";
  import {genTree} from "@/utils";
  import {upUrl, upHeaders} from "@/api/file";
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  const defaultmaterial = {
    name: null,
    number: null,
    specification: null,
    unit: null,
    type: null,
    piece_count: null,
    sort_str: null,
    count_safe: 0,
    processes: [],
    file:null,
  };
  export default {
    components: {Pagination},
    data() {
      return {
        material: defaultmaterial,
        materialList: {
          count: 0,
        },
        upHeaders: upHeaders(),
        upUrl: upUrl(),
        fileList: [],
        processOptions: [],
        options_: {
          // "1": '成品',
          // "2": '半成品',
          "3": '主要原料',
          "4": '辅助材料',
          "5": '加工工具',
          "6": '辅助工装',

        },
        options: [
          /*{
          value: 1,
          label: '成品'
        }, {
          value: 2,
          label: '半成品'
        }, */
          {
          value: 3,
          label: '主要原料'
        }, {
          value: 4,
          label: '辅助材料'
        }, {
          value: 5,
          label: '加工工具'
        }, {
          value: 6,
          label: '辅助工装'
        }],
        unitoptions: [
          {
            value: '块',
            label: '块'
          }, {
            value: '套',
            label: '套'
          }, {
            value: '个',
            label: '个'
          }, {
            value: 'm2',
            label: 'm2'
          }, {
            value: '瓶',
            label: '瓶'
          }, {
            value: 'g',
            label: 'g'
          }, {
            value: 'kg',
            label: 'kg'
          }, {
            value: '卷',
            label: '卷'
          }, {
            value: '张',
            label: '张'
          }, {
            value: '支',
            label: '支'
          }, {
            value: '袋',
            label: '袋'
          }, {
            value: '米',
            label: '米'
          },
        ],
        listQuery: {
          type:3,
          page: 1,
          page_size: 20,
        },
        activeName: "3",
        listLoading: true,
        dialogVisible: false,
        dialogType: "new",
        rule1: {
          name: [{required: true, message: "请输入", trigger: "blur"}],
          number: [{required: true, message: "请输入", trigger: "blur"}],

        },
      };
    },
    computed: {},
    watch: {},
    created() {
      this.getList();
      this.getProcessList();
    },
    methods: {
      checkPermission,
      handlePreview(file) {
        if ("url" in file) {
          window.open(file.url);
        } else {
          window.open(file.response.data.path);
        }
      },
      handleUpSuccess(res, file, filelist) {
        this.material.file = res.data.id;
      },
      handleRemove(file, filelist) {
        this.material.file = null;
      },
      //物料详情
      handledetail(scope){
        this.$router.push({name: "MaterialDetail", params: { id: scope.row.id,type: scope.row.type }, })
      },
      //选项卡切换
      handleClick(tab) {
        this.listLoading = true;
        this.listQuery.type = tab.name;
        getMaterialList(this.listQuery).then((response) => {
          if (response.data) {
            this.materialList = response.data;
          }
          this.listLoading = false;
        });
      },
      getList() {
        this.listLoading = true;
        getMaterialList(this.listQuery).then((response) => {
          if (response.data) {
            this.materialList = response.data;
          }
          this.listLoading = false;
        });
      },
      //工序清单
      getProcessList() {
        getProcessList().then((res) => {
          this.processOptions = res.data.results;
        });
      },
      //检查表
      handlebind(scope) {
        let materialItem = sessionStorage.getItem('materialItem');
        let materialType = sessionStorage.getItem('materialType');
        if(materialItem){
          sessionStorage.removeItem('materialItem');
          sessionStorage.setItem('materialItem',JSON.stringify(scope.row));
        }else{
          sessionStorage.setItem('materialItem',JSON.stringify(scope.row));
        }
        if(materialType){
          sessionStorage.removeItem('materialType');
          sessionStorage.setItem('materialType','30');
        }else{
          sessionStorage.setItem('materialType','30');
        }
        this.$router.push({name: "MaterialDO", params: {id: scope.row.id}})
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      resetFilter() {
        this.activeName = "";
        this.listQuery = {
          page: 1,
          page_size: 20,
        };
        this.getList();
      },
      handleCreate() {
        this.material = Object.assign({}, defaultmaterial);
        this.dialogType = "new";
        this.dialogVisible = true;
        if (this.material.file) {
          this.fileList = [
            {
              name: this.process.instruction_.name,
              url: this.process.instruction_.path,
            },
          ];
        }
        this.$nextTick(() => {
          this.$refs["Form"].clearValidate();
        });
      },
      handleEdit(scope) {
        this.fileList = [];
        this.material = Object.assign({}, scope.row); // copy obj
        this.dialogType = "edit";
        this.dialogVisible = true;
        if (this.material.file) {
          this.fileList = [
            {
              name: this.material.file_.name,
              url: this.material.file_.path,
            },
          ];
        }
        this.$nextTick(() => {
          this.$refs["Form"].clearValidate();
        });
      },
      handleDelete(scope) {
        this.$confirm("确认删除?", "警告", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "error",
        })
          .then(async () => {
            await deleteMaterial(scope.row.id);
            this.getList();
            this.$message.success("成功");
          })
          .catch((err) => {
            console.error(err);
          });
      },
      async confirm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            const isEdit = this.dialogType === "edit";
            if (isEdit) {
              updateMaterial(this.material.id, this.material).then((res) => {
                if (res.code >= 200) {
                  this.getList();
                  this.dialogVisible = false;
                  this.fileList = [];
                  this.$message.success("成功");
                }
              });
            } else {
              createMaterial(this.material).then((res) => {
                if (res.code >= 200) {
                  this.getList();
                  this.dialogVisible = false;
                  this.fileList = [];
                  this.$message.success("成功");
                }
              });
            }
          } else {
            return false;
          }
        });
      },
    },
  };
</script>

