<template>
  <div class="app-container">
    <el-card>
        
    <div style="margin-top: 10px">
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate"
        >新增工序</el-button
      >
    </div>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-table
        v-loading="listLoading"
        :data="processList.results"
        border
        fit
        stripe
        highlight-current-row
        max-height="600"
         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">{{ scope.row.name }}</template>
        </el-table-column>
         <el-table-column label="生产车间" >
          <template slot-scope="scope"  v-if="scope.row.workshop_">{{ scope.row.workshop_.name }}</template>
        </el-table-column>
      <el-table-column align="center" label="指导书">
          <template slot-scope="scope" v-if="scope.row.instruction_">
            <el-link :href="scope.row.instruction_.path" >{{scope.row.instruction_.name}}</el-link>
          </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
              type="primary"
              @click="handleAdd(scope)"
              >添加子工序</el-link
            >
            <el-link
              v-if="checkPermission(['process_update'])"
              @click="handleEdit(scope)"
              >编辑</el-link
            >
            <el-link
              v-if="checkPermission(['process_delete'])"
              type="danger"
              @click="handleDelete(scope)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="processList.count > 0"
        :total="processList.count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑工序' : '新增工序'"
    >
      <el-form
        ref="Form"
        :model="process"
        label-width="100px"
        label-position="right"
        :rules="rule1"
      >
        <el-form-item label="工序名称" prop="name">
          <el-input v-model="process.name" placeholder="工序名称" />
        </el-form-item>
        <el-form-item label="工序编号" prop="number">
          <el-input v-model="process.number" placeholder="工序编号" />
        </el-form-item>
        <el-form-item label="生产车间" prop="workshop">
            <treeselect v-model="process.workshop"  :options="workoptions" placeholder="所属部门"/>
        </el-form-item>
       <el-form-item label="指导书内容" prop="instruction_content">
          <el-input  type="textarea"  :rows="3" v-model="process.instruction_content" placeholder="指导书内容" />
        </el-form-item>
         <el-form-item label="指导书" prop="template" v-if="dialogVisible">
          <el-upload
          ref="upload"
          :action="upUrl"
          :on-preview="handlePreview"
          :on-success="handleUpSuccess"
          :on-remove="handleRemove"
          :headers="upHeaders"
          :file-list="fileList"
          :limit="1"
          accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx"
        >
          <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 { getProcessList, createProcess,updateProcess,deleteProcess } from "@/api/mtm";
import checkPermission from "@/utils/permission";
import { getOrgAll } from "@/api/org"
import { upUrl, upHeaders } from "@/api/file";
import Treeselect from '@riophae/vue-treeselect'

import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { genTree } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
const defaultprocess = {
  name: "",
  number: "",
};
export default {
  components: { Pagination,Treeselect },
  data() {
    return {
      process: defaultprocess,
     processList: {
        count: 0,
      },
       upHeaders: upHeaders(),
      upUrl: upUrl(),
      fileList:[],
      workoptions:[],
      listQuery: {
        page: 1,
        page_size: 20,
      },
     
      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.getOrgAll();
   
  },
  methods: {
    checkPermission,
    //工序列表
    getList() {
      this.listLoading = true;
      getProcessList(this.listQuery).then((response) => {
        if (response.data) {
          this.processList = response.data;
        }
        this.listLoading = false;
      });
    },
    //生产车间
     getOrgAll() {
      this.treeLoding = true;
      getOrgAll().then(response => {
        this.workoptions = genTree(response.data);
        this.treeLoding = false;
      });
    },
     handlePreview(file) {
      if ("url" in file) {
        window.open(file.url);
      } else {
        window.open(file.response.data.path);
      }
    },
    handleUpSuccess(res, file, filelist) {
      this.process.instruction = res.data.id;
    },
    handleRemove(file, filelist){
      this.process.instruction = null;
    },
   //添加子工序
   handleAdd(scope)
   {
     this.$router.push({name: "Step", params: { id: scope.row.id }, })
   },
    

    
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        page_size: 20,
      }
      this.getList();
    },
    handleCreate() {
      this.process = Object.assign({}, defaultprocess);
      this.dialogType = "new";
      this.dialogVisible = true;
       this.fileList=[];
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
   
    handleEdit(scope) {
      this.process = Object.assign({}, scope.row); // copy obj
      this.dialogType = "edit";
      this.dialogVisible = true;
       if (this.process.instruction) {
        this.fileList = [
          {
            name:this.process.instruction_.name,
            url: this.process.instruction_.path,
          },
        ];
      }
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteProcess(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) {
            updateProcess(this.process.id, this.process).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          } else {
            createProcess(this.process).then((res) => {
              if (res.code >= 200) {
                this.getList();
                 this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
