<template>
  <div class="jtjyTeamContent">
    <div class="searchContent bg-white p-4 pb-0 my-4 rounded-6px flex justify-between">
      <el-form ref="ruleFormRef" :inline="true" :model="searchForm" size="small">
        <el-form-item>
          <remote-select placeholder="全部所属机构" v-model="searchForm.tjt_cydw_id" url="/school/main/index" :fields="['id', 'sm_name']"></remote-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="initData">查询</el-button>
    </div>
    <div class="resultDiv bg-white p-4 rounded-6px">
      <div class="operateDiv flex justify-between">
        <div>
          <el-button type="primary" @click="handleAddEdit()">新增</el-button>
          <el-button type="primary" @click="handleExport">导出</el-button>
          <import-button url="/txwx/jtjy_td" :d="{tjk_id: parentId}" @success="initData">
            <template #text>批量导入</template>
          </import-button>
          <el-button type="danger" @click="handleDelete()">删除</el-button>
        </div>
        <div class="flex items-center space-x-4">
          <el-input v-model="searchForm.keyword" placeholder="请输入搜索的关键词" size="small" :suffix-icon="Search" />
          <el-button type="primary" @click="initData">搜索</el-button>
        </div>
      </div>
      <div class="tableList">
        <div class="tableDiv my-20px">
          <el-table :data="tableData" size="large" height="100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column v-for="(item, index) in columnData" :key="index" :prop="item.key" :label="item.name" :width="item.width" :min-width="item.minWidth" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button type="primary" text @click="handleAddEdit(row)">编辑</el-button>
                <el-divider direction="vertical" />
                <el-button type="primary" text @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex justify-end">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="limit" :page-sizes="[10, 20, 50, 100]" :pager-count="5" :small="true" layout="total,sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="新增/编辑" width="650px" destroy-on-close :close-on-click-modal="false" @close="handleClose">
      <el-form ref="ruleFormRef" :inline="true" :model="ruleForm" label-width="120px" size="small" class="grid grid-cols-2 pr-30px">
        <el-form-item label="成员账号:">
          <!-- <el-input v-model="ruleForm.tjt_cymc"></el-input> -->
          <remote-user-select size="small" class="w-full" v-model="ruleForm.tjt_cyid" v-model:model-name="ruleForm.tjt_cyzh" v-model:model-real-name="ruleForm.tjt_cymc" :change="initCreateName" :d="{user_role_id:'75'}" showKey="user_name"></remote-user-select>
        </el-form-item>
        <el-form-item label="成员名称:">
          <el-input v-model="ruleForm.tjt_cymc"></el-input>
        </el-form-item>
        <el-form-item label="成员单位名称:">
          <remote-select class="w-full" v-model="ruleForm.tjt_cydw_id" v-model:model-name="ruleForm.tjt_cydwmc" url="/school/main/index" :fields="['id', 'sm_name']"></remote-select>
        </el-form-item>
        <el-form-item label="学科/专业:">
          <remote-select class="w-full" v-model="ruleForm.tjt_xkzy_id" v-model:model-name="ruleForm.tjt_xkzy" to="jcxxgl_zyflgl_xk" :fields="['tjzx_id', 'tjzx_xkmc']"></remote-select>
        </el-form-item>
        <el-form-item label="成员排序:">
          <el-input v-model="ruleForm.tjt_sort" placeholder="数值小展示靠前" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div class="mt-5 text-center">
        <el-button type="primary" plain @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
const router = useRouter();
const parentId = router.currentRoute.value.params.id;

const searchForm = ref({});

watch(() => searchForm.value, () => {
  initData();
}, { deep: true })

const total = ref(0)
const limit = ref(10)
const currentPage = ref(1);
const columnData = ref([
  {
    name: "ID",
    key: "tjt_id",
  },
  {
    name: "成员名称",
    key: "tjt_cymc",
  },
  {
    name: "成员单位名称",
    key: "tjt_cydwmc",
  },
  {
    name: "学科",
    key: "tjt_xkzy",
  },
  {
    name: "排序",
    key: "tjt_sort",
  }
]);
const tableData = ref([]);

if (parentId) {
  initData();
}

async function initData() {
  let data = {
    page: currentPage.value,
    limit: limit.value,
    tjk_id: parentId
  };
  let res = await request({ url: "/txwx/jtjy_td/index", data: Object.assign(data, searchForm.value) });
  if (res.code == 1) {
    tableData.value = res.data.page_data;
    total.value = Number(res.data.total_rows);
  }
}

function handleSizeChange(val) {
  limit.value = val;
  currentPage.value = 1;
  initData();
}

function handleCurrentChange(val) {
  currentPage.value = val;
  initData();
}

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

const dialogVisible = ref(false);
const currentId = ref("");
const ruleForm = ref({
  tjt_cymc: "",
  tjt_cyid: "",
  tjt_cyzh: "",
  tjt_cydw_id: "",
  tjt_cydwmc: "",
  tjt_xkzy_id: "",
  tjt_xkzy: "",
  tjt_sort: "",
  tjk_id: parentId
});
const handleClose = (type) => {
  dialogVisible.value = false;
  for (let key in ruleForm.value) {
    if (key != "tjk_id") {
      ruleForm.value[key] = "";
    }
  }
  currentId.value = "";

  if (type == 1) {
    initData();
  }
}

function initCreateName(data) {
  // if (typeof data == "string") {
  //   ruleForm.value.tjt_cymc = data;
  // }
}

const handleAddEdit = async (data) => {
  if (data) {
    currentId.value = data?.tjt_id;

    let res = await request({ url: "/txwx/jtjy_td/detail", data: { tjt_id: data.tjt_id } });
    if (res.code == 1) {
      for (let key in ruleForm.value) {
        ruleForm.value[key] = res.data.one_info[key];
      }
      ruleForm.value.tjt_cyid = ruleForm.value.tjt_cyid && ruleForm.value.tjt_cyid != 0 ? ruleForm.value.tjt_cyid : "";
    }
  }
  dialogVisible.value = true;
}


const submit = async () => {
  let data = {
    txwx_jtjy_td: ruleForm.value
  }
  let res = {};
  if (currentId.value == "") {
    res = await request({ url: "/txwx/jtjy_td/add", data });
  } else {
    data.tjt_id = currentId.value;
    res = await request({ url: "/txwx/jtjy_td/edit", data });
  }
  if (res.code == 1) {
    ElMessage.success("保存成功！");
    handleClose(1);
  }
}

const handleDelete = (row) => {
  if (!row && multiSelection.value.length == 0) {
    ElMessage.error("请先选择数据！");
    return
  }
  ElMessageBox.confirm('确定要删除该数据吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: "warning",
  })
    .then(async () => {
      let tjt_id;
      if (row) {
        tjt_id = row.tjt_id;
      } else {
        tjt_id = [];
        multiSelection.value.map(item => {
          tjt_id.push(item.tjt_id);
        })
      }
      let res = await request({ url: "/txwx/jtjy_td/delete", data: { tjt_id: tjt_id } });
      if (res.code == 1) {
        ElMessage.success("删除成功！");
        initData();
      }
    })
    .catch(() => { })
}


const handleExport = () => {
  let arr = [];
  multiSelection.value.map((item) => {
    arr.push(item.tjt_id);
  });
  let obj = {
    limit: "99999",
    tjk_id: parentId,
    tjt_id: arr.join(",")
  };
  download("/txwx/jtjy_td/index", obj);
}
</script>

<style lang="scss" scoped>
@use "~/styles/table.scss";
@use "~/styles/pagination.scss";
.jtjyTeamContent {
  .resultDiv {
    .tableList {
      height: calc(100% - 32px);
      .tableDiv {
        height: calc(100% - 32px - 50px);
      }
    }
  }
  .el-dialog {
    .el-button--primary.is-plain {
      background: unset;
      &:hover {
        color: var(--el-color-primary);
      }
    }
    .el-button + .el-button {
      margin-left: 50px;
    }
  }
}
</style>