<template>
  <!-- 全景课堂 -->
  <div class="ssysKcbglManage" v-loading="loading">
    <div class="searchDiv flex">
      <div class="flex">
        <el-button size="default" type="success" @click="handleDownload">导出</el-button>
        <el-button size="default" type="primary" @click="handleAddOrEdit()">新建</el-button>
        <el-button size="default" type="danger" @click="handleRemove()">删除</el-button>
      </div>
      <div class="flex">
        <el-input v-model="keyword" size="default" placeholder="请输入搜索的关键词" :suffix-icon="Search" />
        <el-button size="default" type="primary" @click="initData" style="margin-left: 10px;">搜索</el-button>
      </div>
    </div>

    <div class="searchContent">
      <div class="tableList">
        <div class="tableDiv">
          <el-table ref="multipleTableRef" :data="tableData" height="100%" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="tm_title" width="" label="标题" show-overflow-tooltip>
              <template #default="{row}">
                <span style="color: #00A3FF;">{{row.tm_title}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="tm_cjr" width="" label="创建人" show-overflow-tooltip></el-table-column>
            <el-table-column prop="tm_lx" width="" label="类型" show-overflow-tooltip></el-table-column>
            <el-table-column prop="tm_glr_json" width="" label="关联的人" show-overflow-tooltip></el-table-column>
            <el-table-column label="详情" width="">
              <template #default="{row}">
                <el-button text size="default" type="primary" @click="lookDetail(row)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{row}">
                <el-button text size="default" type="primary" @click="handleAddOrEdit(row.tm_id)">编辑</el-button>
                <span class="split">|</span>
                <el-button text size="default" type="primary" @click="handleRemove(row.tm_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="paginationDiv">
          <el-pagination background layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange" :page-size="limit" :currentPage="currentPage"></el-pagination>
        </div>
      </div>
    </div>

    <el-dialog :width="showAttach?'80%':'600px'" v-model="dialogVisible" :title="dialogTitle" custom-class="commonDialog" :show-close="showAttach?true:false" @close="handleClose(2)" :close-on-click-modal="false">
      <preview-attach v-if="showAttach" :commonUrl="commonUrl" :suffix="suffix" style="width: 100%; height: 600px;"></preview-attach>

      <el-form v-if="!showAttach" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm" size="default">
        <div class="flex">
          <el-form-item label="标题" prop="tm_title">
            <el-input v-model="ruleForm.tm_title" />
          </el-form-item>
          <el-form-item label="类型" prop="tm_lx">
            <el-select v-model="ruleForm.tm_lx" placeholder=" ">
              <el-option v-for="item in typeData" :key="item.v" :label="item.n" :value="item.v" />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="创建人" prop="tm_cjr">
            <el-input readonly v-model="ruleForm.tm_cjr" />
          </el-form-item>
          <el-form-item label="关联" prop="tm_glr">
            <remote-load-multi-select v-if="dialogVisible" url="/user/main/index" multiple :fields="['user_id','user_realname']" :d="{user_role_id:'75'}" v-model="ruleForm.tm_glr" v-model:model-name="ruleForm.tm_glr_json"></remote-load-multi-select>
          </el-form-item>
        </div>
        <el-form-item label="上传附件" prop="tm_file">
          <file-upload-progress v-if="dialogVisible" v-model:part="ruleForm.tm_file" :limit="1">
            <template #default>
              <div class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9">
                <i-akar-icons:plus class="text-xl" />
              </div>
            </template>
          </file-upload-progress>
        </el-form-item>
      </el-form>
      <template v-if="!showAttach" #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose(2)">取消</el-button>
          <el-button type="primary" @click="commitData(ruleFormRef)">发送</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup >
import { reactive, ref } from "vue";
import { user } from '~/store/user';
import { Search } from "@element-plus/icons-vue";
import { download } from "~/utils/request";
import { tzggList, tzggAdd, tzggEdit, tzggDelete, tzggDetail } from "./api";

const loading = ref(false);

const typeData = ref([]);
const ruleFormRef = ref(null);
const ruleForm = reactive({
  tm_title: "",
  tm_lx: "",
  tm_cjr: user.user_realname,
  tm_glr: "",
  tm_file: ""
});
const rules = reactive({
  tm_title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  tm_lx: [{ required: true, message: "请选择类型", trigger: "change" }],
  tm_cjr: [{ required: true, message: "请输入创建人", trigger: "blur" }],
  tm_glr: [{ required: true, message: "请选择关联人", trigger: "change" }],
  tm_file: [{ required: true, message: "请上传附件", trigger: "submit" }],
});

const tableData = ref([]);
const total = ref(0);
const limit = ref(10);
const currentPage = ref(1);
function handleCurrentChange(val) {
  currentPage.value = val;
  initData();
}

const keyword = ref("");
initData(1);
async function initData(flag) {
  let obj = {
    limit: limit.value,
    page: currentPage.value,
    keyword: keyword.value,
    site: "tyyx"
  };
  loading.value = true;
  let data = await tzggList(obj);
  total.value = parseInt(data.total_rows);
  tableData.value = data.page_data;
  loading.value = false;

  if (flag == 1) {
    typeData.value = data.table_structure.field.tm_lx.option;
  }
}

const dialogVisible = ref(false);
const dialogTitle = ref("");
const currentId = ref("");
const handleAddOrEdit = (id) => {
  dialogVisible.value = true;
  if (id) {
    currentId.value = id;
    dialogTitle.value = "编辑";
    initDetailInfo();
  } else {
    dialogTitle.value = "添加";
  }
};

const initDetailInfo = async () => {
  let data = await tzggDetail({ tm_id: currentId.value });
  for (let key in ruleForm) {
    ruleForm[key] = data.one_info[key];
  }
}

const showAttach = ref(false);
const commonUrl = ref("");
const suffix = ref("");
const lookDetail = (data) => {
  dialogVisible.value = true;
  showAttach.value = true;
  dialogTitle.value = "详情";

 commonUrl.value = data.tm_file; 
  suffix.value = commonUrl.value.substr(commonUrl.value.lastIndexOf(".") + 1);
}

const handleClose = (type) => {
  dialogVisible.value = false;
  currentId.value = "";
  showAttach.value = false;
  commonUrl.value = "";
  suffix.value = "";
  resetForm(ruleFormRef.value);
  if (type == 1) {
    initData();
  }
}

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

const commitData = (formEl) => {
  if (!formEl) return;

  formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      let data = {
        tzgg_main: ruleForm,
      };
      if (currentId.value == "") {
        await tzggAdd(data);
      } else {
        data = Object.assign({ tm_id: currentId.value }, data);
        await tzggEdit(data);
      }
      loading.value = false;
      ElMessage.success("保存成功！");
      handleClose(1);
    } else {
      console.log("error submit!", fields);
    }
  });
}

const handleRemove = async (tm_id) => {
  if ((tm_id == undefined || tm_id == "") && multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除的数据！");
    return;
  }
  ElMessageBox.confirm("是否确定删除当前数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    buttonSize: "default",
  })
    .then(async () => {
      loading.value = true;
      if (tm_id != undefined && tm_id != "") {
        await tzggDelete({ tm_id });
      } else {
        let arr = [];
        multipleSelection.value.map((item) => {
          arr.push(item.tm_id);
        });
        await tzggDelete({ tm_id: arr });
      }
      ElMessage.success("删除成功！");
      loading.value = false;
      initData();
    })
    .catch(() => { });
};

const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const handleDownload = () => {
  let arr = [];
  multipleSelection.value.map((value) => {
    arr.push(value.tm_id);
  });
  let obj = {
    limit: limit.value,
    page: currentPage.value,
    keyword: keyword.value,
    checkedidstring: arr.join(","),
  };

  download("/tzgg/main/index", obj);
};
</script>

<style lang="scss" scoped>
@import "~/styles/dialog.scss";
.ssysKcbglManage {
  height: calc(100vh - 50px - 2rem);
  .flex {
    display: flex;
    align-items: center;
    .el-form-item {
      flex: 1;
    }
  }
  .searchDiv {
    // height: 62px;
    background: #fff;
    // border-radius: 6px;
    // box-shadow: 0 0 5px rgba($color: #000000, $alpha: 0.1);
    // padding: 0 20px;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #e3e3e3;
    ::v-deep .el-button {
      height: 32px;
    }
  }
  .searchContent {
    margin-top: 12px;
    height: calc(100% - 53px - 12px);
    background: #fff;
    border-radius: 6px;
    // box-shadow: 0 0 5px rgba($color: #000000, $alpha: 0.1);
    // padding: 0 20px;
    .tableList {
      height: 100%;
      // height: calc(100% - 52px - 10px);
      position: relative;
      .tableDiv {
        // background: #ddd;
        height: calc(100% - 42px);
        .el-button {
          padding: 0;
        }
        .split {
          color: #00a3ff;
          margin: 0 10px;
        }
      }
      .paginationDiv {
        position: absolute;
        bottom: -5px;
        padding: 3px;
        width: 100%;
        display: -webkit-box;
        -webkit-box-pack: end;
      }
    }
  }
}
</style>