<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="单位名称" prop="name">
        <el-input
          v-model="queryParams.name"
          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="['business:unit:add']"
        >新增</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="['business:unit: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="['business:unit:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleStencil"
          v-hasPermi="['business:unit:export']"
        >导出上传模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <FileUploader
          uploadUrl="/business/unit/importData "
          uploadButtonText="导入"
          v-hasPermi="['business:unit:import']"
          @refreshTable="()=>{getList();getTree()}"
        />
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row>
      <el-col :span="4">
        <el-tree :data="treeData" :props="{label:'name',value:'id',children: 'childrenList'}" :default-expand-all="true"></el-tree>
      </el-col>
      <el-col :span="20">
        <el-table v-loading="loading" :data="unitList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" type="index" />
          <el-table-column label="公司名称" align="center" prop="name">
            <template>{{treeData[0]?treeData[0].name:''}}</template>
          </el-table-column>
          <el-table-column label="单位名称" align="center" prop="name" />
          <el-table-column label="修改时间" align="center" prop=" createTime" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.updateTime||scope.row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:unit:edit']"
              >编辑</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDetail(scope.row)"
                v-hasPermi="['business:unit:edit']"
              >详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:unit:remove']"
                style="color:#ff9292;"
              >删除</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-col>
    </el-row>

    <!-- 添加或修改维修站点-单位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px" @submit.native.prevent>
        <el-form-item label="单位名称">
          {{treeData[0]?treeData[0].name:''}}
        </el-form-item>
        
        <el-form-item label="单位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入单位名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 单位详情对话框 -->
    <el-dialog title="编辑单位" :visible.sync="open2" width="1000px" append-to-body @close="detailTable=[]">
      <div style="width: 100%;display:flex;align-items:center;justify-content:space-between;padding-bottom: 20px;">
        <div>
          公司：{{treeData[0]?treeData[0].name:''}}
          <div style="display:inline-block;width:20px;height:10px;"></div>
          单位：{{form.name}}
        </div>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd1"
          v-hasPermi="['business:unit:add']"
        >新增</el-button>
      </div>
      <el-table v-loading="loading1" :data="detailTable">
        <el-table-column label="序号" align="center" type="index"/>
        <el-table-column label="单位名称" align="center" prop="unitName" />
        <el-table-column label="车间名称" align="center" prop="name" />
        <el-table-column label="修改时间" align="center" prop=" createTime" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime||scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate1(scope.row)"
              v-hasPermi="['business:workshop:edit']"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete1(scope.row)"
              v-hasPermi="['business:workshop:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 添加或修改维修站点-车间对话框 -->
    <el-dialog :title="form1.id?'修改车间':'新增车间'" :visible.sync="open1" width="500px" append-to-body @submit.native.prevent>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="90px">
        <el-form-item label="单位名称">
          公司：{{treeData[0]?treeData[0].name:''}}
          <div style="display:inline-block;width:20px;height:10px;"></div>
          单位：{{form.name}}
        </el-form-item>
        <el-form-item label="车间名称" prop="name">
          <el-input v-model="form1.name" placeholder="请输入车间名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUnit, getUnit, delUnit, addUnit, updateUnit, getUnitTree } from "@/api/business/unit";
import { listWorkshop, getWorkshop, delWorkshop, addWorkshop, updateWorkshop } from "@/api/business/workshop";
export default {
  name: "Unit",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维修站点-单位表格数据
      unitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        isEnable: undefined,
         createTime: undefined,
        isDelete: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "单位名称不能为空", trigger: "blur" }
        ],
      },
      treeData:[],
      open1: false,
      detailTable: [],
      loading1:false,
      open2: false,
      form1: {},
      // 表单校验
      rules1: {
        name: [
          { required: true, message: "单位名称不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getTree()
  },
  methods: {
    getTree(){
      getUnitTree().then(res=>{
        this.treeData=[
          {name:this.$store.state.user.completeName,id:'',childrenList:res.data},
        ]
      })
    },
    /** 查询维修站点-单位列表 */
    getList() {
      this.loading = true;
      listUnit(this.queryParams).then(response => {
        this.unitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        isEnable: undefined,
        createBy: undefined,
         createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        isDelete: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增-单位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id 
      getUnit(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改维修站点-单位";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateUnit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getTree()
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addUnit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getTree()
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids.map(item=>item.id);
      this.$modal.confirm('是否确认删除单位名称为'+(row.name||this.ids.map(item=>item.name).join(','))+'的数据项？').then(() => {
        this.loading = true;
        return delUnit(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.getTree()
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/unit/export', {
        ...this.queryParams,
        ids: this.ids.map(item=>item.id).join(',')
      }, `单位目录`)
    },
    /** 模板按钮操作 */
    handleStencil() {
      this.download("business/unit/importTemplate", {}, `单位目录模板`);
    },
    handleDetail(row){
        if(row)this.form={...row};
        this.open2=true;
        this.loading1=true
      listWorkshop({
        unitId: this.form.id,
        pageNum: 1,
        pageSize: 999
      }).then(res=>{
        this.detailTable=res.rows
      }).finally(()=>{
        this.loading1=false
      })
    },
    handleAdd1(){
      this.form1={
        unitId: this.form.id,
        unitName: this.form.name,
        isDelete: 0,
        isEnable: 1,
      }
      console.log(this.form1,this.form);
      this.open1=true
    },
    handleUpdate1(row){
      this.form1={...row}
      this.open1=true;
    },
    handleDelete1(row) {
      const ids = row.id
      this.$modal.confirm('是否确认删除车间名称为'+(row.name)+'的数据项？').then(() => {
        this.loading1 = true;
        return delWorkshop(ids);
      }).then(() => {
        this.loading1 = false;
        this.handleDetail();
        this.getTree();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading1 = false;
      });
    },
    // 取消按钮
    cancel1() {
      this.open1 = false;
    },
    /** 提交按钮 */
    submitForm1() {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form1.id != null) {
            updateWorkshop(this.form1).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open1 = false;
              this.handleDetail();
              this.getTree();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addWorkshop(this.form1).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open1 = false;
              this.handleDetail();
              this.getTree();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
  }
};
</script>
