<template>
  <div>
    <div class="bigBox">
      <div class="zy-right">
        <div class="titleBox">
          <div class="title">目标指标库列表</div>
        </div>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
        <el-divider />
        <div class="btnBox">
          <!-- 只有省、市、安全部门才能增删改 -->
          <el-button type="primary" @click="add" v-if="ssdept.orgBizType == '04'">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
          <el-button type="primary" v-if="ssdept.orgBizType == '04'" @click="downloadTemplate('00', '目标指标上传模板')">
            <el-icon>
              <Download />
            </el-icon>
            <span>模板下载</span>
          </el-button>
          <el-button type="primary" @click="uploadFile" v-if="ssdept.orgBizType == '04'">
            <el-icon>
              <UploadFilled />
            </el-icon>
            <span>批量上传</span>
          </el-button>
          <!-- 文件上传小东西 -->
          <input type="file" style="display: none;" @change="changeFile" ref="fileBtn">
        </div>

        <!-- 表格 -->
        <section class="eltab3">
          <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData"
            :tableloading="tableloading" :tableHeight="'100%'" :isSelect="false" style="width: 100%;" :isSort="false">
            <template #typeId="{ row }">
              <dict-tag :options="D_BZ_TARGET_ITEM_TYP" :value="row.typeId" :tag="false" />
            </template>
            <template #targetLevel="{ row }">
              <div style="display: flex;">
                <span v-for="(it, index) in row.targetLevel" :key="index"
                  style="margin: 0 2px;display: flex;align-items: center;">
                  <dict-tag :options="D_BZ_SSXJB" :value="it" :tag="false" />,
                </span>
              </div>
            </template>
            <template #targetValueType="{ row }">
              <dict-tag :options="D_BZ_TARGET_ITEM_JSFS" :value="row.targetValueType" :tag="false" />
            </template>
            <template #sfgl="{ row }">
              <dict-tag :options="D_BZ_SF" :value="row.sfgl" :tag="false" />
            </template>
            <template #actions="{ row }">
              <span class="operedit" v-if="ssdept.orgBizType == '04'" @click="handlexg(row)">
                <el-icon>
                  <EditPen />
                </el-icon>编辑</span>
              <el-popconfirm v-if="ssdept.orgBizType == '04'" confirm-button-text="是" cancel-button-text="否"
                icon-color="red" title="确定要删除?" @confirm="handledelete(row)">
                <template #reference>
                  <span span class="operdel" size="small">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    删除</span>
                </template>
              </el-popconfirm>
              <span class="operesee" @click="handleSee(row)">
                <el-icon>
                  <View />
                </el-icon>查看</span>
            </template>
          </MOSTY.Table>
        </section>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
            @changeSize="handleSizeChange" />

        </div>
      </div>
    </div>
    <!-- 新增、修改详情 -->
    <div v-if="addDiaShow" class="dialod">
      <el-dialog :title="title" v-model="addDiaShow" stripe width="850px" top="10%" :before-close="handleClose">
        <div class="config">
          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="135px" :disabled="loadType == '2'"
            style="display: block;" :inline="true">
            <el-form-item label="目标子项名称:" prop="targetName">
              <el-input v-model="ruleForm.targetName" clearable style="width: 602px" maxlength="50"></el-input>
            </el-form-item>
            <el-form-item label="级别:" prop="targetLevel">
              <el-select v-model="ruleForm.targetLevel" multiple style="width: 602px">
                <el-option v-for="item in D_BZ_SSXJB" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="类别:" prop="typeId">
              <el-select v-model="ruleForm.typeId" clearable style="width: 217px;">
                <el-option v-for="item in D_BZ_TARGET_ITEM_TYP" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="目标计算方式:" prop="targetValueType">
              <el-select v-model="ruleForm.targetValueType" clearable style="width: 217px;">
                <el-option v-for="item in D_BZ_TARGET_ITEM_JSFS" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="目标:" prop="targetValue">
              <el-input v-model="ruleForm.targetValue" :max="100" type="number" style="width: 217px;">
                <template #append v-if="ruleForm.targetValueType == '2'">%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="是否关联:" prop="sfgl">
              <el-select v-model="ruleForm.sfgl" clearable style="width: 217px;">
                <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="ruleForm.sfgl == '1' && userId == '000000'" label="sql语句:">
              <el-input v-model="ruleForm.sql" clearable style="width: 602px" type="textarea"
                :autosize="{ minRows: 4, maxRows: 15 }"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" v-if="loadType != '2'" @click="handleSave(ruleFormRef)" :loading="loading">
              <el-icon>
                <DocumentChecked />
              </el-icon>
              <span>保存</span>
            </el-button>
            <el-button @click="handleClose" type="primary">
              <el-icon>
                <DocumentDelete />
              </el-icon>
              <span>关闭</span>
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
// 引入
import { reactive, watch, onMounted, getCurrentInstance, ref, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { getItem } from "@/utils/storage";
import * as MOSTY from "@/components/MyComponents/index";
import { isString } from '@/utils/tools.js';
import { getApi, postApi, uploadfilApi } from "@/api/tobAcco_api.js";
const { proxy } = getCurrentInstance();
const { D_BZ_TARGET_ITEM_JSFS, D_BZ_TARGET_ITEM_TYP, D_BZ_SF, D_BZ_SSXJB } =
  proxy.$dict("D_BZ_TARGET_ITEM_JSFS", "D_BZ_TARGET_ITEM_TYP", "D_BZ_SF", "D_BZ_SSXJB");
const tableloading = ref(false)
import { downloadTemplate } from "@/utils/tools.js";
const ssdept = getItem("deptId");
const userId = getItem("USERID");
const addDiaShow = ref(false);
const ruleFormRef = ref();
const loadType = ref("0");
const fileBtn = ref()
const title = ref(""); //弹窗标题
const loading = ref(false); //新增保存按钮截流
const searchArr = reactive([
  {
    showType: "select",
    prop: "typevalue",
    width: '250px',
    options: D_BZ_TARGET_ITEM_TYP,
    placeholder: "请选择目标/指标类型"
  }
]);
//表单数据
const ruleForm = ref({});
//规则校验
const rules = reactive({
  targetName: [{ required: true, message: "目标子项目名称不能为空", trigger: "blur" }],
  typeId: [{ required: true, message: "级别不能为空", trigger: "blur" }],
  targetValueType: [{ trigger: "blur", required: true, message: "目标计算方式不能为空" }],
  targetValue: [
    { required: true, message: '请输入目标值', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入目标值'));
        } else if ((value < 0 || value > 100) && ruleForm.value.targetValueType == '2') {
          callback(new Error('只能输入0-100的数字'));
        } else if (value.length > 10 && ruleForm.value.targetValueType == '1') {
          callback(new Error('数字大小超出限制，长度为10'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  sfgl: [{ required: true, message: '请选择是否关联', trigger: 'blur' }],
  targetLevel: [{ required: true, message: '请选择级别', trigger: 'blur' }],
})
// 数据
const typevalue = ref("");
// 分页
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20
});
// 表格数据
const tableData = ref([]);
//是否有更新权限
const isEdit = ref(false)
const pageData = reactive({
  tableColumns: [
    {
      title: "名称",
      prop: "targetName"
    },
    {
      title: "目标/指标",
      prop: "typeId",
      slot: true
    },
    {
      title: "适用范围",
      prop: "targetLevel",
      slot: true
    },
    {
      title: "数值类型",
      prop: "targetValueType",
      slot: true
    },
    {
      title: "值",
      prop: "targetValue"
    },
    {
      title: "是否关联",
      prop: "sfgl",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  tableData: []
})
//监听目标计算方式
watch(
  () => ruleForm.value.targetValueType,
  (val) => {
    if (!ruleForm.value.id) {
      if (val == "1") {
        ruleForm.value.targetValue = "0";
      } else {
        ruleForm.value.targetValue = "";
      }
    }
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  const orgLevel = ssdept.orgLevel.substring(0, 1)
  // 判断权限
  if ((orgLevel == '1' || orgLevel == '2') && ssdept.orgBizType == '04') {
    isEdit.value = true
  }
  getTabList();
});
// 查询数据
const onSearch = (obj) => {
  typevalue.value = obj.typevalue;
  getTabList();
};
// 导入模板数据
const uploadFile = () => {
  nextTick(() => {
    fileBtn.value.click()
  })
}
// 获取文件
const changeFile = () => {
  nextTick(() => {
    let file = fileBtn.value.files[0]
    if (!file) { return; }
    let data = new FormData()
    data.append('file', file);
    uploadfilApi(data, `/mosty-jcgl/target/batchUpload`).then(() => {
      ElMessage.success("批量上传成功");
      listQuery.pageCurrent = 1;
      getTabList();
    }).finally(() => {
      fileBtn.value.value = ''
    })
  })
}
//获取表格数据
function getTabList() {
  tableloading.value = true
  const params = listQuery.value;
  params.typeId = typevalue.value;
  postApi(params, "/mosty-jcgl/target/getTargetList").then((res) => {
    tableloading.value = false;

    res.records.forEach(el => {
      if (el.targetValueType === '2' && !el.targetValue.includes('%')) {
        el.targetValue = el.targetValue + '%'
      }
      if (el.targetLevel) {
        el.targetLevel = el.targetLevel.split(',')
      }
    });
    pageData.tableData = res.records
    pageData.pageConfiger.total = res.total
  }).catch((err) => {
    tableData.value = []
    tableloading.value = false;
  })
}
//获取数据详情
function getTabXq(id) {
  getApi({}, `/mosty-jcgl/target/getTargetById/${id}`).then((res) => {
    if (res) {
      if (res.targetValue.includes('%')) {
        res.targetValue = res.targetValue.split("%")[0]
      }
      if (res.targetLevel) {
        res.targetLevel = res.targetLevel.split(",")
      }
      ruleForm.value = res;
    }
  });
}

//新增目标子项
function add() {
  tableloading.value = false;
  title.value = "目标子项新增";
  addDiaShow.value = true;
  ruleForm.value = {};
}
const handlexg = (row) => {
  getTabXq(row.id);
  loadType.value = "1";
  title.value = "目标子项修改";
  addDiaShow.value = true;
};
const handleSee = (row) => {
  getTabXq(row.id);
  loadType.value = "2";
  title.value = "目标子项详情";
  addDiaShow.value = true;
};
//删除数据
const handledelete = (row) => {
  postApi({}, "/mosty-jcgl/target/getTargetSC/{id}?id=" + row.id).then(() => {
    ElMessage.success('删除成功')
    getTabList();
  })
};

//关闭
const handleClose = () => {
  if (loadType.value != '2') {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        loadType.value = "0";
        addDiaShow.value = false;
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
      })
      .catch(() => {
        // catch error
      })
  } else {
    loadType.value = "0";
    addDiaShow.value = false;
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
  }

};

//保存
const handleSave = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      ruleForm.value.targetLevel = ruleForm.value.targetLevel ? ruleForm.value.targetLevel.toStrong() : ''
      if (ruleForm.value.id) {
        postApi(ruleForm.value, "/mosty-jcgl/target/getTargetXG")
          .then(() => {
            ElMessage.success("修改成功");
            addDiaShow.value = false;
            loading.value = false;
            getTabList();
          }).finally(() => {
            loading.value = false;
            ruleForm.value.targetLevel = ruleForm.value.targetLevel && isString(ruleForm.value.targetLevel) ? ruleForm.value.targetLevel.split(',') : ruleForm.value.targetLevel
          })
      } else {
        postApi(ruleForm.value, "/mosty-jcgl/target/getTargetXZ")
          .then(() => {
            ElMessage.success("新增成功");
            addDiaShow.value = false;
            loading.value = false;
            getTabList();
          }).finally(() => {
            loading.value = false;
            ruleForm.value.targetLevel = ruleForm.value.targetLevel && isString(ruleForm.value.targetLevel) ? ruleForm.value.targetLevel.split(',') : ruleForm.value.targetLevel
          })
      }
    } else {
      ElMessage.warning("请输入必填项!");
    }
  });
};

//关闭弹窗
const closeDialog = () => {
  loading.value = false;
  addDiaShow.value = false;
};
//分页
const handleSizeChange = (val) => {
  listQuery.value.pageSize = val;
  pageData.pageConfiger.pageSize = val;
  getTabList();
};
const handleCurrentChange = (val) => {
  listQuery.value.pageCurrent = val;
  pageData.pageConfiger.pageCurrent = val;
  getTabList();
};
</script>

<style lang="scss" scoped>
.eltab3 {
  height: calc(100vh - 375px)
}

::v-deep .el-dialog__body {
  height: 28vh !important;
}

.zy-right {
  width: 100%;
}

.dialod {
  ::v-deep .el-form-item__content {
    flex-wrap: nowrap !important;
  }

  .config {
    .el-form {
      margin-top: 10px;
      display: block;
    }

    .el-form-item {
      text-align: center;
    }
  }

  .titleBox {
    align-items: center;
    margin: 0;
    padding: 0;
    height: 39px;
    border: 1px solid rgb(32, 75, 54);
    padding: 20px;
  }

  .el-form-item__content {
    flex-wrap: nowrap;
  }

  .el-collapse {
    border-color: var(--el-color-primary);
    height: 460px;
  }
}

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
