<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="keyWord">
          <el-input
            v-model="queryParams.keyWord"
            placeholder="请输入"
            clearable maxlength="20"
            style="width: 300px"
            @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"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            size="mini"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="tableListData" @selection-change="handleSelectionChange" height="800">
        <el-table-column type="selection"    align="center" width="55"  />
        <el-table-column align="center" prop="protectionCode" :show-overflow-tooltip="true"  width="120"  label="定值单编号"   />
        <el-table-column align="center" prop="protectionName" :show-overflow-tooltip="true"  width="120"  label="定值单名称"   />
        <el-table-column align="center" prop="protectionDate"        :show-overflow-tooltip="true"  width="120"  label="定值单日期"   />
        <el-table-column align="center" prop="deviceName"       :show-overflow-tooltip="true"  width="120"  label="设备所属"      />
        <el-table-column align="center" prop="oneDevice"         :show-overflow-tooltip="true"  width="150"  label="一次设备名称" />
        <el-table-column align="center" prop="protectionDevice"       :show-overflow-tooltip="true"  width="120"  label="保护装置名称" />
        <el-table-column align="center" prop="protectionDeviceModel"       :show-overflow-tooltip="true"  width="120"  label="保护装置型号" />
        <el-table-column align="center" prop="protectionDeviceVersion"       :show-overflow-tooltip="true"  width="120"  label="装置版本"      />
        <el-table-column align="center" prop="remark"       :show-overflow-tooltip="true"  width="120"  label="备注"        />
        <el-table-column align="center" prop="description"       :show-overflow-tooltip="true"  width="120"  label="说明"        />

        <el-table-column label="操作"     align="center" width="250" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleView(scope.row)"
            >解析结果查看</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              style="color: red;"
              @click="handleDelete(scope.row)"
            >删除</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="700px" append-to-body>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 基础设置 -->
            <el-tab-pane label="" name="baseSetting" style="height: 400px;">
                <el-form ref="baseForm" :model="baseForm" :rules="baseFormRules" label-width="150px">
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="保护定值单图片" prop="imgUrl">
                        <el-upload
                              :http-request="
                                  (obj) => imgUpLoad(obj, 'fileUrl')
                              "
                              action="#"
                              :limit="1"
                              :file-list="fileList"
                              :show-file-list="true"
                              list-type="picture-card"
                              accept=".png, .jpg, .jpeg"
                              :on-success="handleAvatarSuccess"
                              :before-upload="handleBeforeUpload"
                              :class="{ disabled:uploadDisabled }"
                              :on-preview="handlePictureCardPreview"
                              :on-remove="handleRemove"
                          >
                          <i class="el-icon-plus avatar-uploader-icon"></i>
                          </el-upload>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
            </el-tab-pane>
        </el-tabs>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="titleView+''" :visible.sync="openView" width="700px" append-to-body>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 基础设置 -->
            <el-tab-pane label="" name="baseSetting" style="height: 400px;">
                <el-form  label-width="150px">
                  <el-row>
                    <el-col :span="24">
                        阜阳电网继电保护装置整定值通知书
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24"></el-col>
                    <el-col :span="24"></el-col>
                    <el-col :span="24"></el-col>
                    <el-col :span="24"></el-col>
                  </el-row>
                </el-form>
            </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
  </template>

  <script>
    import {
        listDept,
        getDept,
        delDept,
        addDept,
        updateDept,
        listDeptExcludeChild,
    } from '@/api/system/dept'
    import { getProtectionOrderListPageApi,editProdectionApi,deleteProtectionApi } from "@/api/protection/index";
    import base64 from 'base-64';
    import { getToken } from '@/utils/auth'
    import { imgUpLoadTwo } from '@/api/system/upload'
    import { downloadFileByUrl } from '@/utils/download'
    import Treeselect from '@riophae/vue-treeselect'
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'
    export default {
        name: "",
        dicts: ["sys_certificate_type"],
        components: { Treeselect },
        data() {
            return {
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                //表格数据
                tableListData: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                openView:false,
                titleView: "",
                checked: false,
                userNameFlage:false,
                protectionIds:[],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    keyWord:null,
                },
                activeName:"baseSetting",
                deviceData:{},
                // 表单参数
                baseForm: {
                  protectionId:""
                },
                // 表单校验
                baseFormRules: {
                    substationName: [
                        { required: true, message: "变电站名称不能为空", trigger: "blur" }
                    ]
                },
                fileList: [],//图片
                checkUrlList: [],//图片
                checkUrlNameList: [],//图片
                dialogVisible:false,//图片弹窗
                dialogImageUrl:"",//图片弹窗
            };
        },
        mounted(){
            this.getList();
        },
        computed: {
            //图片上传1张后，隐藏上传框
            uploadDisabled() {
                return this.checkUrlList.length > 0
            },
        },
        methods: {
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            /** 查询列表 */
            getList() {
                this.loading = true;
                let param = {
                    "pageNum":this.queryParams.pageNum,
                    "pageSize":this.queryParams.pageSize,
                    "type":'1',
                    "keyWord":this.queryParams.keyWord
                }
                console.log("param",param)
                // let str = base64.encode(JSON.stringify(param))
                // console.log({"content":str})
                getProtectionOrderListPageApi(param).then(response => {
                    this.tableListData = response.rows;
                    this.total = Number(response.total);
                    this.loading = false;
                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.baseForm = {
                    substationName:"",
                    runTime:""
                };
                this.resetForm("baseForm");
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "新增";
                console.log("this.baseForm",this.baseForm);
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                this.open = true;
                this.baseForm = Object.assign({}, row)
                this.fileList=[{url:this.baseForm.imgUrl}]
                this.checkUrlList=[this.baseForm.imgUrl]
                this.checkUrlNameList=[this.baseForm.imgName]
                // this.$set(this,"metadata",row.deviceMetadata)
                this.title = "修改";
            },
            handleView(row) {
                this.reset();
                this.openView = true;
                const obj = Object.assign({}, row)
                this.titleView = "查看";
            },
            handleTabClick(tab, event) {
                console.log(tab, event);
            },
            /** 提交按钮 */
            submitForm: function() {
                console.log("this.fileList",this.fileList);
                console.log("this.checkUrlList",this.checkUrlList);
                console.log("this.checkUrlNameList",this.checkUrlNameList);
                console.log("this.baseForm",this.baseForm);
                editProdectionApi({checkUrlList:this.checkUrlList,checkUrlNameList:this.checkUrlNameList,protectionId:this.baseForm.protectionId,type:'0'}).then(response => {
                    console.log("editProdectionApi",response);
                    this.getList();
                    this.open = false;
                    this.$modal.msgSuccess("操作成功");
                    return;
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
              var protectionIdRow="";
                if(row!=undefined &&row.protectionId!=null&&row.protectionId!=undefined){
                      protectionIdRow=row.protectionId.split(" ");
                }
                const protectionIds = protectionIdRow || this.protectionIds;
                console.log("protectionIds",protectionIds);
                this.$modal.confirm('是否确认删除数据项？').then(() => {
                  deleteProtectionApi({protectionIds:protectionIds}).then(response => {
                      console.log("deleteProtectionApi",response);
                      this.getList();
                      this.$modal.msgSuccess("删除成功");
                      return;
                  });
                }).catch(() => {});
            },
            formatDate(date) {
                // 格式化为 YYYY-MM-DD
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            },

            // 多选框选中数据
            handleSelectionChange(selection) {
              this.protectionIds = selection.map(item => item.protectionId)
            },
            // 图片上传
            imgUpLoad(param, name, index) {
                param.type = 'dishes'
                this.btnLoading=true;
                imgUpLoadTwo(param).then((res) => {
                    if (res.code == 200) {
                        this.checkUrlList.push(res.data.url)
                        this.checkUrlNameList.push(res.data.name)
                        this.$set(this.baseForm,"imageUrl",res.data.url)
                    } else {
                        this.fileList=[]
                        this.checkUrlList=[]
                        this.checkUrlNameList=[]
                        this.$set(this.baseForm,"imgUrl",'')
                        this.$modal.msgError(res.msg)
                    }
                    this.btnLoading=false;
                }).catch((error) => {
                    this.fileList=[]
                    this.checkUrlList=[]
                    this.checkUrlNameList=[]
                    this.btnLoading=false;
                    this.$modal.msgError(error)
                })
            },
            handleAvatarSuccess(res, file) {
                console.log('success')
            },
            // 上传之前
            handleBeforeUpload(file) {
                const isLt = file.size / 1024 / 1024 < 5
                if (!isLt) {
                    this.$modal.msgError(`图片大小不能超过 5 MB`)
                    return false
                }
            },
            handleRemove(file, fileList) {
                let sum = 0
                this.checkUrlNameList.forEach((item, index) => {
                    if (item == file.name) {
                        sum = index
                    }
                })
                this.checkUrlNameList.splice(sum, 1)
                this.checkUrlList.splice(sum, 1)
                this.$set(this.baseForm,"imageUrl",'')
            },
            //图片点击查看
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url
                this.dialogVisible = true
            },

        }
    };
  </script>
  <style scoped lang="scss">
    .form-title{
        display: flex;
        align-items: flex-end;
        // width: 100%;
        // height: 40px;
        background: #e7f0fa;
        border-left: 3px solid #46a6ff;
        margin: 10px 0;
        padding: 5px;
    }
    .form-item{
        width: 100%;
        font-size: 14px !important;
    }
  </style>
