<script setup>
import {Search } from '@element-plus/icons-vue'
import swiper from "/images/swiper.png";
import { user } from "~/store/index";
import { downLoadFile } from "~/utils/download";
import { userDetailStore } from "~/store/detail";
import axios from 'axios';
const detailStore = userDetailStore();
const router = useRouter();

const params = ref({
  create_user_id: user.value.user_id,
});

const fields = ref({
  id: "azz_id_v2",
  name: "az_name",
  img: "az_img",
  time: "create_dateline",
  file: "az_file",
});

const gradeList = ref([
  { label: '一年级', value: '1' },
  { label: '二年级', value: '2' },
  { label: '三年级', value: '3' },
  { label: '四年级', value: '4' },
  { label: '五年级', value: '5' },
  { label: '六年级', value: '6' }
])

onMounted(() => {
  inintData();
})

const status = ref();
const statusData = ref([
  {
    name: "专业",
    status: "1",
  },
  {
    name: "标签",
    status: "2",
  },
]);

const pingLabel = ref('zyfl_zy_v2');

const total = ref(0);

const page = ref(1);
const limit = ref(10);
const keyword = ref("");
//初始化
const inintData = () => {
  let transObj = {};
  if (status.value == "1") {//专业
    pingLabel.value = "zyfl_zy_v2";
    transObj = {
      page:page.value,
      limit:limit.value,
      azz_name_v2:keyword.value,
    }
  } else {
    pingLabel.value = "zyfl_bq_v2";
    transObj = {
      page:page.value,
      limit:limit.value,
      azb_name_v2:keyword.value,
    }
  }
  request({
    url: `/aimooc/${pingLabel.value}/index`,
    data: transObj,
  })
    .then(res => {
      if (res.code == "1") {
        if (status.value == "1") {
          tableDataPro.value = res.data.page_data;
          total.value = Number(res.data.total_rows)
        } else {
          tableDataLab.value = res.data.page_data;
          total.value = Number(res.data.total_rows)
        }
      }
    })
    .catch(err => { console.log('err', err) });
}

function handleCurrentChange(val) {
  page.value = val
  inintData()
}

changeStatus("1");
function changeStatus(data) {
  status.value = data;
  keyword.value = '';
  inintData();
}

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

//批量删除
function handleMutiDelete() {
  let arr = "";
  if (status.value == "1") {
    arr = multipleSelection.value.map((item) => {
      return item['azz_id_v2'];
    });
  } else {
    arr = multipleSelection.value.map((item) => {
      return item['azb_id_v2'];
    });
  }

  if ( multipleSelection.value.length == 0) {
    return ElMessage.warning("请先选择需要删除的数据");
  }
  ElMessageBox.confirm("确定要删除这些数据吗？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let pinX = "";
      if (status.value == "1") {
        pinX="azz_id_v2"
      } else {
        pinX="azb_id_v2"
      }
      const requestData = {};
      requestData[pinX] = arr;
      const { code } = await request({
        url: `/aimooc/${pingLabel.value}/delete`,
        data:requestData,
      });
      if (code === "1") {
        ElMessage.success("删除成功！");
        inintData();
      }
    })
    .catch(() => {});
}
const markLabel = ref("add");
//新增
function handleAdd() {
  if (status.value == "1") {
    formPro.value = {
      proName: '',
      proCampus: '',
      proSub: '',
    };
    dialogFormVisible_addEditPro.value = true;
  } else {
    formLab.value = {
      labName: '',
    };
    dialogFormVisible_addEditLab.value = true;
  }
  markLabel.value = "add";
}
//导出
function handleExport() {
  let allPa = {}
  if (status.value == "1") {
    allPa.excel_file_name = "资源分类管理-专业";
    allPa.url = '/aimooc/zyfl_zy_v2/index';
  } else {
    allPa.excel_file_name = "资源分类管理-标签";
    allPa.url = '/aimooc/zyfl_bq_v2/index';
  }
  let data = {};
  let { token } = user.value;
  const params = Object.assign({ token, limit: 10000, page: 1, api: 'xls',excel_file_name:allPa.excel_file_name }, data);
  const paramsStr = Object.entries(params).map(([k, v]) => `${k}=${v}`).join('&');
  const el = document.createElement('a');
  var url = allPa.url;
  const href = `${window.GLOBAL_CONFIG.api}${url}?${paramsStr}`;
  el.setAttribute('href', href)
  el.click()
}
//批量导入
function handleBatchInport() {
  appendixList.value = [];
  dialogFormVisible_upload.value = true;
}

const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? 'warning-row' : 'success-row';
}
const tableDataPro = ref([]);
const tableDataLab = ref([]);

const currentId = ref()
//单个编辑
const singleEdit = (index, row) => {
  markLabel.value = "edit";
  let tempObj = {};
  if (status.value == "1") {//专业
    currentId.value = row.azz_id_v2;
    tempObj = {
      azz_id_v2:row.azz_id_v2
    }
  } else {
    currentId.value = row.azb_id_v2;
    tempObj = {
      azb_id_v2:row.azb_id_v2
    }
  }
  request({
    url: `/aimooc/${pingLabel.value}/detail`,
    data: tempObj,
  })
    .then(res => {
      if (res.code == "1") {
        let responseData = res.data.one_info;
        if (status.value == "1") {
          formPro.value = {
            proName: responseData.azz_name_v2,
            proCampus: responseData.azz_ssxy_id_v3,
            proSub: responseData.azz_ssnj_v2_option_k,
          }
          dialogFormVisible_addEditPro.value = true;
        } else {
          formLab.value = {
            labName: responseData.azb_name_v2,
          }
          dialogFormVisible_addEditLab.value = true;
        }

      }
    })
    .catch(err => { console.log('err', err); });
}
//单个删除
const singleDel = (index, row) => {
  let tempObj = {};
  if (status.value == "1") {
    tempObj = {
      azz_id_v2:row.azz_id_v2
    }
  } else {
    tempObj = {
      azb_id_v2:row.azb_id_v2
    }
  }
  request({
    url: `/aimooc/${pingLabel.value}/delete`,
    data: tempObj
  })
    .then(res => {
      if (res.code == "1") {
        ElMessage({
          message: res.msg,
          type: 'success',
        })
        inintData();
      }
    })
    .catch(err => {console.log('err',err); });
}

const dialogFormVisible_addEditPro = ref(false);
const dialogFormVisible_addEditLab = ref(false);

const formLabelWidth = '100%';
const formPro = ref({
  proName: '',
  proCampus: '',
  proSub: '',
})

const rulesPro = ({
  proName: [
    { required: true, message: '请输入专业名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度为1到8个字符', trigger: 'blur' },
  ],
  proCampus: [
    {
      required: true,
      message: '请选择所属学院',
      trigger: 'change',
    },
  ],
  proSub: [
    {
      required: true,
      message: '请选择所属年级',
      trigger: 'change',
    },
  ],
});
const ruleFormRefPro = ref();
const formLab = ref({
  labName: '',
})
const rulesLab = ({
  labName: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 8, message: '长度为1到8个字符', trigger: 'blur' },
  ],
});
const ruleFormRefLab = ref();

let campusName = ref("");
const handleChange = (val) => {
  campusName.value = campData.find(item => item.camp_id == val).camp_name;
}


const handleSubmit = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let whichS = "";
      let transObj = {};
      if (markLabel.value == "add") {
        if (status.value == "1") {
          transObj = {
            aimooc_zyfl_zy_v2: {
              azz_name_v2: formPro.value.proName,
              azz_ssxy_id_v3: formPro.value.proCampus,
              azz_ssxy_name_v3: campusName.value,
              azz_ssnj_v2:formPro.value.proSub
            }
          }
        } else {
          transObj = {
            aimooc_zyfl_bq_v2: {
              azb_name_v2: formLab.value.labName,
            }
          }
        }
        whichS="add"
      } else {
        if (status.value == "1") {
          transObj = {
            aimooc_zyfl_zy_v2: {
              azz_name_v2: formPro.value.proName,
              azz_ssxy_id_v3: formPro.value.proCampus,
              azz_ssxy_name_v3: campusName.value,
              azz_ssnj_v2:formPro.value.proSub
            }
          }
          transObj.azz_id_v2 = currentId.value;
        } else {
          transObj = {
            aimooc_zyfl_bq_v2: {
              azb_name_v2: formLab.value.labName,
            }
          }
          transObj.azb_id_v2 = currentId.value;
        }
        whichS="edit"
      }

      request({
        url: `/aimooc/${pingLabel.value}/${whichS}`,
        data: transObj,
      })
      .then(res => {
        if (res.code == "1") {
          ElMessage({
            message: res.msg,
            type: 'success',
          });

          inintData();
        }
      })
      .catch(err => { console.log('err', err); });
      dialogFormVisible_addEditPro.value = false;
      dialogFormVisible_addEditLab.value = false;
    } else {
      console.log('error submit!', fields)
    }
  })
}

//导入dialog
const dialogFormVisible_upload = ref(false)
const appendixList = ref([]);

/**附件上传网络请求*/
const appendixHttpRequest = (param) => {
  const token = user.value.token
  let updateUrl =""
if (status.value == "1") {
  updateUrl = window.GLOBAL_CONFIG.api + '/aimooc/zyfl_zy_v2/import';
} else {
  updateUrl = window.GLOBAL_CONFIG.api + '/aimooc/zyfl_bq_v2/import';
}
  let file = param.file;
  let formData = new FormData();
  formData.append('api', 'json');
  formData.append('site', 'aimk');
  formData.append('token', token);
  // formData.append('urltype', 1)
  formData.append('file', file);
  const instance = axios.create({
    withCredentials: true, // 一定要加这个，不用设置什么请求头
  });
  instance.post(
    updateUrl,
    formData
  )
    .then(res => {
      let responseData = res.data;
      ElMessage({
        message: responseData.msg,
        type: 'success',
      })
      dialogFormVisible_upload.value = false;
      inintData();
    })
    .catch(error => {
      console.log(error);
    })

}

/**附件删除*/
const handleRemoveAppendix = (file, fileList) => {
  console.log(file, fileList);
  var fileName = file.name;
  appendixList.value = appendixList.value.filter(item => item.name !== fileName);
}

function formatTime(val) {
  // 将整数转为毫秒数
  const timestamp = val * 1000;
  // 创建 Date 对象
  const date = new Date(timestamp);
  // 获取年、月、日、时、分、秒
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  // 拼接成年月日时分秒格式
  const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return formattedDate;
}



initCamp()
let campData = $ref([]);
// 学院信息
function initCamp(){
  request({
    baseURL: window.GLOBAL_CONFIG.uc,
    url:'/school/main/get_camp',
    data:{
      sm_id: user.value.sm_info?.sm_id
    }
  }).then(res=>{
    const { code, data } = res;
    if (code === "1") {
      campData = data.camp;
    }
  })
}

</script>

<template>
  <div class="h-full flex flex-col">
    <div class="my-15px flex items-center justify-between">
      <div class="flex space-x-6">
        <div v-for="(item, index) in statusData" :key="index" class="pageTitle" :class="status === item.status && 'active'" @click="changeStatus(item.status)">{{ item.name }}</div>
      </div>
      <div class="flex items-center">
        <el-button plain class="ml-33px h-42px w-130px del_btn"  @click="handleMutiDelete"> 删除 </el-button>
        <el-button type="primary" class="ml-20px h-42px w-130px" @click="handleAdd" >新增</el-button>
        <el-button type="primary" class="ml-20px h-42px w-130px" @click="handleExport" >导出</el-button>
        <el-button type="primary" class="ml-20px h-42px w-130px" @click="handleBatchInport" v-if="false" >批量导入</el-button>
        <el-input v-model="keyword" class="ml-20px h-42px rounded-8px" placeholder="搜索" :prefix-icon="Search" @change="inintData" />

      </div>
    </div>
    <div class="contN" v-if="status==1">
      <!-- :row-class-name="tableRowClassName" -->
      <el-table ref="multipleTableRef" :data="tableDataPro"  @selection-change="handleSelectionChange" >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="azz_name_v2" label="专业名称" width="180" />
        <el-table-column prop="azz_name_v2" label="所属学校" >
          <template #default="scope">{{ user.dw }}</template>
        </el-table-column>
        <el-table-column prop="azz_ssxy_name_v3" label="所属学院" v-show="campData.length>0">
          <template #default="scope">{{ scope.row.azz_ssxy_name_v3 }}</template>
        </el-table-column>
        <!-- <el-table-column  prop="azz_ssxy_name_v3" label="所属学院" /> -->
        <el-table-column label="所属年级"  >
          <template #default="scope">
            <span v-if="scope.row.azz_ssnj_v2=='1'">一年级</span>
            <span v-if="scope.row.azz_ssnj_v2=='2'">二年级</span>
            <span v-if="scope.row.azz_ssnj_v2=='3'">三年级</span>
            <span v-if="scope.row.azz_ssnj_v2=='4'">四年级</span>
            <span v-if="scope.row.azz_ssnj_v2=='5'">五年级</span>
            <span v-if="scope.row.azz_ssnj_v2=='6'">六年级</span>
          </template>
        </el-table-column>
        <el-table-column  label="创建时间" >
          <template #default="scope">{{ formatTime(scope.row.create_dateline) }}</template>
        </el-table-column>
        <el-table-column label="操作 " width="180">
          <template #default="scope">
            <i class="option_normal editIcon" @click="singleEdit(scope.$index, scope.row)"></i>
            <i class="option_normal ml-4 delIcon" @click="singleDel(scope.$index, scope.row)"></i>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="contN" v-if="status==2">
      <el-table ref="multipleTableRef" :data="tableDataLab"  @selection-change="handleSelectionChange" >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="azb_name_v2" label="标签名称"  />
        <el-table-column  label="创建时间" >
          <template #default="scope">{{ formatTime(scope.row.create_dateline) }}</template>
        </el-table-column>
        <el-table-column label="操作 " width="180">
          <template #default="scope">
            <i class="option_normal editIcon" @click="singleEdit(scope.$index, scope.row)"></i>
            <i class="option_normal ml-4 delIcon" @click="singleDel(scope.$index, scope.row)"></i>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex justify-end box-border px-80px pb-30px mt-20px" style="color: #000;">
      <el-pagination
      v-model:current-page="page"
      v-model:page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @current-change="handleCurrentChange"
    />
    </div>

    <!-- 新增（专业） -->
    <el-dialog v-model="dialogFormVisible_addEditPro" title="新增/编辑" width="20%" class="rounded-xl dialogBox">
      <el-form ref="ruleFormRefPro" :model="formPro" :rules="rulesPro" >
        <div class="labelTxt">专业名称</div>
        <el-form-item label="" prop="proName" >
            <el-input class="Input" v-model="formPro.proName" autocomplete="off" />
        </el-form-item>
        <template v-if="campData.length>0">
          <div class="labelTxt">所属学院</div>
          <el-form-item label="" prop="proCampus" class="belongSchool">
            <el-select v-model="formPro.proCampus" @change="handleChange" placeholder="请选择所属学院" >
              <el-option v-for="(item,index) in campData" :key="index" :label="item.camp_name" :value="item.camp_id" />
            </el-select>
          </el-form-item>
        </template>
        <div class="labelTxt">所属年级</div>
        <el-form-item label="" prop="proSub" >
          <el-select class="Input" v-model="formPro.proSub" placeholder="请选择所属年级" >
            <el-option v-for="(item,index) in gradeList" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="flex justify-center dialog-footer">
          <el-button type="primary" class="w-70"  @click="handleSubmit(ruleFormRefPro)" >确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入 -->
    <el-dialog v-model="dialogFormVisible_upload" title="导入" width="35%">
      <el-upload class="upload-demo" action="#" :http-request="appendixHttpRequest" :on-remove="handleRemoveAppendix"
        :limit="1" :file-list="appendixList" accept=".xlsx,.xls">
        <el-button size="small" type="primary">点击上传</el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持文件类型:.xlsx(.xls)文件格式
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible_upload = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 新增（标签） -->
    <el-dialog v-model="dialogFormVisible_addEditLab" title="新增/编辑" width="20%" class="rounded-xl dialogBox">
      <el-form ref="ruleFormRefLab" :model="formLab" :rules="rulesLab" >
        <div class="labelTxt">标签名称</div>
        <el-form-item label="" prop="labName" >
            <el-input class="Input" v-model="formLab.labName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="flex justify-center dialog-footer">
          <el-button type="primary" class="w-70"  @click="handleSubmit(ruleFormRefLab)" >确认</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<route lang="json">
  {
    "meta":{
      "title":"资源分类管理",
      "img":"/images/zyflgl.png",
      "sort":0,
       "hiddenJs":true
    }
  }
</route>

<style lang="scss" scoped>
@use "~/styles/page.scss";
@use "~/styles/dialog.scss";
@use "~/styles/checkbox.scss";
:deep {
  .el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

  .el-input__wrapper {
    // background: #f7f7f7;
    box-shadow: none;
  }
  .form_select {
    width: 100%;
    .el-input__wrapper {
      background: #f3f3f3;
      width: 100%;
    }
    &.el-select .el-input.is-focus .el-input__wrapper {
      box-shadow: none !important;
    }
  }
  .select {
    .el-input__wrapper {
      background: #f3f3f3;
    }
    &.el-select .el-input.is-focus .el-input__wrapper {
      box-shadow: none !important;
    }
  }
  .el-upload {
    width: 100% !important;
  }
  .del_btn {
    background: transparent;
    color: #ff6a55;
    border-color: #ff6a55;
  }
  .pageTitle{
    color: #3f3f44;
  }
  .contN{
    color: #000;
  }
  .option_normal{
    width: 36px;
    height: 36px;
    display: inline-block;
    background-size: contain;
    cursor: pointer;
  }
  .editIcon{
    background: url('/public/images/editIcon.png') no-repeat center center;
  }
  .delIcon{
    background: url('/public/images/delIcon.png') no-repeat center center;
  }
  .el-checkbox .el-checkbox__inner {
    width: 23px;
    height: 23px;
    background: none !important;
  }
  .is-checked {
  background: #fdcb9e;
  border-color: #fdcb9e;
  border-radius: 6px;
}
.dialogBox{
  .el-input__inner{
  background: #f7f7f7;
  border-radius: 6px;
  height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
}
}

.Input .el-input__wrapper{
  padding: 1px 1px;
}
.labelTxt{
  font-size: 12px;
  font-family: PingFang SC, PingFang SC-Regular;
  font-weight: Regular;
  text-align: left;
  color: #3f3f44;
  margin-bottom: 5px;
}
.el-select{
  width: 100%;
}
.el-pagination {
    li.is-active {
      color: green;
    }
    li:hover {
      color: rgba($color: green, $alpha: 0.8);
    }
    .el-input__wrapper {
      background: #f7f7f7;
      box-shadow: none;
    }
  }
}
:deep {
  .belongSchool{
    .el-input__wrapper{
      padding: 1px 0;
    }
  }
}

</style>
