<template>
  <div class="app-container">
   
    <div style="margin-top:6px">
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新增</el-button>
    </div>
    <el-table v-loading="listLoading"
              :data="detectorynoticeList.results"
              style="width: 100%;margin-top:10px;"
              border
              fit
              stripe
              highlight-current-row
              max-height="600">
      <el-table-column type="index" width="50" />

      <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.publishdate }}
        </template>
      </el-table-column>
      <el-table-column label="公告内容">
        <template slot-scope="scope">
          {{ scope.row.note }}
        </template>
      </el-table-column>
      <el-table-column label="重要公告">
        <template slot-scope="scope">
          {{ scope.row.ismportant==true?'是':'否'  }}
        </template>
      </el-table-column>
      <el-table-column label="实验室">
        <template slot-scope="scope">

          <ul style="list-style: none;">
            <li  v-for="(item, index) in scope.row.dettonotice" :key="index" >{{item.name}}</li>
            </ul>
      </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary"
                     size="small"
                     icon="el-icon-edit"
                     :disabled="!checkPermission(['testorg_update'])"
                     @click="handleUpdate(scope)" />
          <el-button type="danger"
                     size="small"
                     icon="el-icon-delete"
                     :disabled="!checkPermission(['testorg_delete'])"
                     @click="handleDelete(scope)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="detectorynoticeList.count>0"
                :total="detectorynoticeList.count"
                :page.sync="listQuery.page"
                :limit.sync="listQuery.page_size"
                @pagination="getList" />
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='update'?'编辑标准':'新增标准'">
      <el-form ref="Form"
               :model="standard"
               label-width="100px"
               label-position="right"
               :rules="rule1">

        <el-form-item label="公告标题" prop="name">
          <el-input v-model="standard.name" placeholder="标题" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishdate">
          <el-date-picker v-model="standard.publishdate"
                          type="datetime"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="重要公告" prop="ismportant">
          <el-switch v-model="standard.ismportant"
                     active-color="#13ce66"
                     inactive-color="#8C969D">
          </el-switch>
        </el-form-item>
        <el-form-item label="公告内容" prop="note">
          <el-input type="textarea"
                    :rows="5"
                    placeholder="内容"
                    v-model="standard.note">
          </el-input>
        </el-form-item>
        <el-form-item label="上传附件" prop="path">
          <el-upload :on-preview="handlePreview"
                     :on-success="handleSuccess"
                     :action="upUrl"
                     :headers="upHeaders"
                     :limit="1"
                     :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>

          </el-upload>
        </el-form-item>
        <el-form-item  prop="path">
          <el-button type="primary" @click="innerVisible = true">选择实验室</el-button>
        </el-form-item>
      </el-form>
      <el-dialog width="30%"
                 title="选择实验室"
                 :visible.sync="innerVisible"
                 append-to-body>

        <el-table ref="staffTable"
                  v-loading="listLoading"
                  :key="tableKey"
                  :data="staffList"
                  border
                  fit
                  highlight-current-row
                  @selection-change="handleStaffChange">
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
          <el-table-column label="编号" align="center">
            <template slot-scope="{row}">
              <span>{{ row.code }}</span>
            </template>
          </el-table-column>

          <el-table-column label="名称" align="center">
            <template slot-scope="{row}">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>

        </el-table>
        <el-button type="primary" @click="modifyStaff">提交</el-button>

      </el-dialog>
      <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 { getTestOrgNoticeList,getTestOrgList, createTestOrgNotice, updateTestOrgNotice, deleteTestOrgNotice } from "@/api/laboratory"
  import { upUrl, upHeaders} from "@/api/file"
  import Pagination from "@/components/Pagination"
  import checkPermission from '@/utils/permission'
  const defaultStandard = {
    id: null,
    name: null,
    publishdate: null,
    ismportant: false,
    note:null
  }
  export default {
    components: { Pagination },
    data() {
      return {
         outerVisible: false,
        innerVisible: false,
        upHeaders: upHeaders(),
        upUrl: upUrl(),
        detectorynoticeList: { count: 0 },
        standard: Object.assign({}, defaultStandard),
        listLoading: true,
        staffList: [],
         tableKey: 0,
        listQuery: {
          page: 1,
          page_size: 20
        },
        
        dialogVisible: false,
        dialogType: 'create',
        rule1: {
         
        },
        fileList: []
      };
    },
    created() {
      this.getList();
      this.getStaffList()
    },
    methods: {
      checkPermission,
       handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      handlePreview(file) {
      if ('url' in file){
        window.open(file.url)
      }else{
        window.open(file.response.data.path)
      }
      
      },
      getStaffList() {
        getTestOrgList().then(response => {

          this.staffList = response.data.results;

        })
      },
    
      getList() {
        this.listLoading = true;
        getTestOrgNoticeList(this.listQuery).then(response => {
          if (response.data) {
            this.detectorynoticeList = response.data
            console.log(this.detectorynoticeList)
          }
          this.listLoading = false;
        });
      },
      resetFilter() {
        this.listQuery = {
          page: 1,
          page_size: 20
        };
        this.getList();
      },
     
    handleStaffChange(rows) {
      this.staffData = [];
      if (rows) {
        rows.forEach(row => {
          if (row) {
            this.staffData.push(row.id);
          }
        });
      }

      },
      modifyStaff() {
        this.standard.dettonotice = this.staffData;
        this.innerVisible = false
      },


    handleSuccess(response, file, fileList) {
      this.standard.path = response.data.path
      },


      handleCreate() {
        this.standard = Object.assign({}, defaultStandard);
        this.fileList = []
        this.dialogType = "create";
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs["Form"].clearValidate();
        });
      },


      handleUpdate(scope) {
        this.standard = Object.assign({}, scope.row) // copy obj
       this.items = [];
        if (this.standard.dettonotice) {
          this.standard.dettonotice.forEach(row => {
          if (row) {
            this.items.push(row.id);
          }

          });
          this.standard.dettonotice = this.items;
        };
        if(this.standard.path){
          this.fileList = [{
          name:this.standard.name,
          url:this.standard.path
        }]
      }
        this.dialogType = 'update'
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs['Form'].clearValidate()
        })
      },
      handleDelete(scope) {
      this.$confirm('确定删除本条数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteTestOrgNotice(scope.row.id).then(res=>{
        this.$message.success('删除成功')
              this.getList()
    })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    
},
 
    
      async confirm(form) {
        this.$refs[form].validate(valid => {
        
          if (valid) {
            const isEdit = this.dialogType === "update";
            if (isEdit) {
              updateTestOrgNotice(this.standard.id, this.standard).then(res => {
             
                  this.getList();
                  this.dialogVisible = false
                  this.$message.success('成功')
                
              });
            } else {
              createTestOrgNotice(this.standard).then(res => {
               
                this.getList();
                this.dialogVisible = false
                this.$message.success('成功')

              }).catch(error => { })
            }
          } else {
            return false;
          }
        });
      }
    }
  };
</script>
