<template>
  <div>
    <MOSTY.PageTree :pageTitle="'年度安全目标/指标'" :searchType="'01'" @getDeptId="getDeptId">
      <template #serach>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="onSearch">
          <template #lable>
            <el-button type="primary" @click="decomposeWindow = true">
              <el-icon>
                <CirclePlus />
              </el-icon>
              <span>分解</span>
            </el-button>
          </template>
        </MOSTY.Search>
        <el-divider />
        <div class="btnBox">
          <el-button type="primary" @click="add">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </div>
      </template>
      <template #table>
        <!-- 表格 -->
        <section class="eltab9">
          <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData"
            :tableloading="tableloading" :tableHeight="'100%'" :isSelect="false" style="width: 100%;" :isSort="false">
            <template #xtZhgxr="{ row }">
              <span> {{ row.xtZhgxr ? row.xtZhgxr : row.xtCjr }}</span>
            </template>
            <template #xtZhgxsj="{ row }">
              <span> {{ row.xtZhgxsj ? row.xtZhgxsj : row.xtCjsj }}</span>
            </template>
            <template #actions="{ row }">
              <div style="display: flex;width: 100%;align-items: center;justify-content: center;">
                <!-- 所属单位代码 = 当前登录所属单位代码 且 当前登录为安全科-->
                <div>
                  <span class="operedit" @click="handleXgbz(row)">
                    <el-icon>
                      <EditPen />
                    </el-icon>编辑</span>
                  <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                    @confirm="handlesc(row)">
                    <template #reference>
                      <span class="operdel" size="small">
                        <el-icon>
                          <Delete />
                        </el-icon>删除</span>
                    </template>
                  </el-popconfirm>
                  <el-popconfirm confirm-button-text="复用" cancel-button-text="取消" icon-color="red"
                    v-if="row.year < new Date().getFullYear()" title="确定要复用当前数据到成为本年度的年度目标/指标?" @confirm="reuse(row)">
                    <template #reference>
                      <span class="operedit" size="small">
                        <el-icon>
                          <RefreshLeft />
                        </el-icon>复用</span>
                    </template>
                  </el-popconfirm>
                </div>
                <span class="operesee" @click="handleck(row)">
                  <el-icon>
                    <Compass />
                  </el-icon>查看</span>
              </div>
            </template>
          </MOSTY.Table>
          <div class="fenye">
            <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
              @changeSize="handleSizeChange" />

          </div>
        </section>
      </template>
    </MOSTY.PageTree>

  </div>
  <!-- 新增修改弹窗 -->
  <div v-if="showAdd">
    <el-dialog :title="title" v-model="showAdd" width="1000px" top="10vh" bottom="10vh" :before-close="handleClose">
      <!-- 新增或修改 -->
      <div class="config" style="overflow-y: auto">
        <el-form ref="fromFrs" :model="params" :rules="rules" label-width="130px" style="display: block;" :inline="true"
          :disabled="isdisabled">
          <el-form-item label="年份：" prop="year">
            <el-select v-model="params.year" style="width: 310px;" disabled>
              <el-option v-for="item in filterYear(5)" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="制定对象：">
            <el-select v-model="params.formulatedObject" style="width: 310px;" @change="changeType"
              :disabled="!isFzr || isEdit">
              <el-option v-for="item in [{ value: '01', label: '单位、部门', disabled: filterqx('isaqbm') != '1' ? true : false }, {
                value: '02', label: '个人'
              }]" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="安全目标/指标：" prop="name">
            <el-input v-model="params.name" clearable style="width: 782px" disabled></el-input>
          </el-form-item>
          <el-form-item label="责任人：" prop="username">
            <el-input v-model="params.username" clearable disabled style="width: 782px;">
              <template #append v-if="params.formulatedObject == '02'">
                <el-button @click="choose()">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="附件：">
            <MOSTY.Upload :widthNumber="784" :limit="4" :nopicer="true" :isImg="false" :ShowfileList="true"
              :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']" v-model="params.files" :showinput="true"
              @filehandleChange="changeFile" />
          </el-form-item>
        </el-form>
      </div>
      <div
        style="display: flex;align-items: center;justify-content: space-between;border-top: 1px dashed grey;padding-top:10px;">
        <div>安全目标/指标子项列表</div>
        <div>
          <el-button type="primary" :disabled="isdisabled" @click="addNew">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增目标/指标子项</span>
          </el-button>
        </div>
      </div>
      <!-- 目标/指标、指标数据表 -->
      <div class="xzmb_box">
        <div class="tabHeight">
          <MOSTY.Table :table-columns="mbtabColumns" :tableData="ruleForm.mbtableData" :isSelect="false"
            style="width: 100%;" :isSort="false" actionsW="240">
            <template #targetValueType="{ row }">
              <dict-tag :options="D_BZ_TARGET_ITEM_JSFS" :value="row.targetValueType" :tag="false" />
            </template>
            <!-- 目标/指标 -->
            <template #target="{ row }">
              <dict-tag v-if="row.targetValueType == '3'" :options="D_BZ_SFDB" :value="row.target" :tag="false" />
              <span v-else>{{ row.target ? row.target : "--" }}{{ row.target && row.targetValueType == 2 ? "%" : ""
                }}</span>
            </template>
            <!-- 完成度 -->
            <template #realTarget="{ row }">
              <dict-tag v-if="row.targetValueType == '3'" :options="D_BZ_SFDB" :value="row.realTarget" :tag="false" />
              <span v-else>{{ row.realTarget ? row.realTarget : "--" }}{{ row.realTarget && row.targetValueType == 2 ?
                "%" : ""
                }}</span>
            </template>
            <template #actions="scope">
              <span style="margin-left:0;" class="operesee" @click="handlesee(scope.row, scope.$index)">
                <el-icon>
                  <Compass />
                </el-icon>查看</span>
              <span v-if="!isdisabled" class="operedit" @click="handlexg(scope.row, scope.$index)"><el-icon>
                  <EditPen />
                </el-icon>编辑
              </span>

              <el-popconfirm v-if="!isdisabled" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                title="确定要删除?" @confirm="handledelete(scope.row, scope.$index)">
                <template #reference>
                  <span class="operdel" size="small">
                    <el-icon>
                      <Delete />
                    </el-icon>删除</span>
                </template>
              </el-popconfirm>
              <span v-if="!isdisabled && scope.row.targetid" class="operedit"
                @click="handFinish(scope.row, scope.$index)"><el-icon>
                  <CircleCheck />
                </el-icon>完结
              </span>
            </template>
          </MOSTY.Table>
        </div>


      </div>
      <template #footer>
        <span class="dialog-footer">

          <el-button type="primary" v-if="!isdisabled" :loading="loading" @click="handleSave(fromFrs)">
            <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>
    <!-- 新增目标/指标指标项 -->
    <Addmbzbx :addShow="showAddlable" :checkIds="checkIds" :title="titletwo" :xqData="xqData" :showType="showType"
      :deptCode="deptData.orgCode.replace('XN', '')" :deptLevel="deptLevel" @changeAddVi="changeAddVi"
      @addData="addDataTab" @finish="finish" />
    <!-- 选择负责人多选 -->
    <ChooseUser v-model="showPeople" :Single="false" :data="memberList" :deptId="deptData.orgCode.replace('XN', '')"
      :searchType="'04'" @choosedUsers="getSonValue" />
  </div>

  <BreakDown :decomposeWindow="decomposeWindow" :deptCode="listQuery.deptCode"
    @setDecomposeWindowState="getDecomposeWindowState"></BreakDown>

</template>

<script setup>
// 引入
import { reactive, watch, ref, getCurrentInstance, onMounted } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue"
import BreakDown from "./compon/breakDown.vue"
import { filterYear } from "@/utils/auth.js"

const { proxy } = getCurrentInstance()
import { getItem } from "@/utils/storage"
import { ElMessage } from "element-plus"
import Addmbzbx from "./compon/addmbzbx.vue"
import * as MOSTY from "@/components/MyComponents/index"
import { filterqx } from "@/utils/auth.js"

const searchArr = reactive([
  {
    showType: "select",
    prop: "year",
    defaultVal: new Date().getFullYear(),
    width: "250px",
    options: filterYear(5)
  }
])
const {
  D_BZ_TARGET_ITEM_JSFS,
  D_BZ_SFDB
} =
  proxy.$dict("D_BZ_TARGET_ITEM_JSFS", "D_BZ_SFDB")
const showType = ref("0")
const showAdd = ref(false) //展示新增弹窗
const isdisabled = ref(false)
const isFzr = ref(false)
const title = ref("") //展示弹窗标题
const fromFrs = ref()
const xqData = ref({}) //子项目详情
const showPeople = ref(false) // 展示人员多选弹窗
const memberList = ref([])
const editIndex = ref(null)
const loading = ref(false) //新增保存按钮截流
const ruleForm = ref({
  mbtableData: [] //新增目标/指标表格数据
})
const showAddlable = ref(false) //安全目标/指标子项新增
const titletwo = ref("") //标题
const ssdept = getItem("deptId")
const tableloading = ref(false)
const isEdit = ref(false)
let decomposeWindow = ref(false)
const deptData = ref({})
let checkIds = ref([])
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  deptCode: "",
  year: new Date().getFullYear()
})
const params = reactive({
  formulatedObject: filterqx("isaqbm") != "1" ? "02" : "01",// 单位部门、个人
  orgCode: ssdept.ssdwdm, //所属单位编码
  orgName: ssdept.ssdwmc, //所属单位名称
  year: new Date().getFullYear() //年份
})
//规则校验
const rules = reactive({
  name: [{
    required: true,
    message: "安全目标/指标不能为空",
    trigger: "blur"
  }],
  year: [{
    required: true,
    message: "年份不能为空",
    trigger: "change"
  }],
  username: [{
    required: true,
    message: "责任人不能为空",
    trigger: "change"
  }]
})
const pageData = reactive({
  tableColumns: [
    {
      title: "年份",
      prop: "year"
    },
    {
      title: "安全目标/指标名称",
      prop: "name"
    },
    {
      title: "单位名称",
      prop: "orgName"
    },
    {
      title: "设置人",
      prop: "xtZhgxr",
      slot: true
    },
    {
      title: "责任人",
      prop: "username"
    },
    {
      title: "设置日期",
      prop: "xtZhgxsj",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  tableData: []
})
const mbtabColumns = reactive([
  {
    title: "目标/指标子项名称",
    prop: "itemname"
  },
  {
    title: "计算方式",
    prop: "targetValueType", // 2: 百分比
    slot: true
  },
  {
    title: "目标/指标",
    prop: "target",
    slot: true
  },
  {
    title: "完成度",
    prop: "realTarget",
    slot: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const zbtabColumns = reactive([
  {
    title: "目标/指标子项名称",
    prop: "itemname"
  },
  {
    title: "计算方式",
    prop: "targetValueType",
    slot: true
  },
  {
    title: "目标/指标",
    prop: "target"
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
onMounted(() => {
  getIscz()
})
//列表查询
const onSearch = (obj) => {
  listQuery.year = obj.year
  listQuery.pageCurrent = 1
  pageData.pageConfiger.pageCurrent = 1
  getDataList()
}

//判断是否可以选择
function getIscz() {
  getApi({}, "/mosty-jcgl/securitychild/isAqyPower").then(res => {
    isFzr.value = res
  })
}

const getDecomposeWindowState = (val) => decomposeWindow.value = val

// 新的文件上传返回
const changeFile = (data) => {
  // params.files = data
}
// 确认人员选择
const getSonValue = (value) => {
  params.userid = ""
  params.username = ""
  if (value && value.length > 0) {
    params.username = value.map(item => {
      return item.userName
    }).toString()
    params.userid = value.map(item => {
      return item.id
    }).toString()
  }
}
// 选择人员弹窗
const choose = () => {
  memberList.value = params.userid ? params.userid.split(",") : []
  showPeople.value = true
}
// 切换单位/部门、个人，如果是部门需要查询部门负责人
const changeType = () => {
  if (params.formulatedObject == "01") {
    getApi({ deptid: deptData.value.orgCode.replace("XN", "") }, `/mosty-jcgl/securitychild/getFzrByDeptid`).then((res) => {
      if (res) {
        params.userid = res.id
        params.username = res.userName
        params.name = `${listQuery.year}年《${deptData.value.orgName}》安全目标/指标`
      } else {
        ElMessage.error("未查询到部门负责人,请先设置后在添加！")
      }
    })
  } else {
    params.userid = ""
    params.username = ""
    params.name = `${listQuery.year}年《${deptData.value.orgName}》人员安全目标/指标`
  }
}
// 选择左侧部门树
const getDeptId = (val) => {
  deptData.value = {
    orgCode: val.id.replace("XN", ""),
    orgName: val.orgname.replace("（本级）", ""),
    orgLevel: val.orglevel
  }
  listQuery.deptCode = val.id
  listQuery.pageCurrent = 1
  getDataList()
}

//获取列表数据
function getDataList() {
  tableloading.value = true
  getApi(listQuery, "/mosty-jcgl/safetarget/getPageList").then((res) => {
    if (res.records) {
      tableloading.value = false
      pageData.tableData = res.records
      pageData.pageConfiger.total = res.total
    }
  }).finally(() => {
    pageData.tableData.value = []
    tableloading.value = false
  })
}

//修改安全目标/指标指标
function handleXgbz(val) {
  params.id = val.id
  title.value = "安全目标/指标修改"
  isEdit.value = true
  isdisabled.value = false
  getAqmbXq(val.id)
}

//查看安全目标/指标指标
function handleck(val) {
  title.value = "安全目标/指标详情"
  isdisabled.value = true
  getAqmbXq(val.id)
}

// 复用往年安全目标/指标指标
const reuse = (val) => {
  let id = val.id
  postApi({}, `/mosty-jcgl/safetarget/reuse/${id}`).then(() => {
    ElMessage.success("复用成功")
    getDataList()
  })
}

//删除安全目标/指标指标
function handlesc(val) {
  let id = val.id
  postApi({}, `/mosty-jcgl/safetarget/delSafeTarget/${id}`).then(() => {
    ElMessage.success("删除成功")
    getDataList()
  })
}

//打开新增弹窗
function add() {
  editIndex.value = null
  ruleForm.value = {
    mbtableData: []
  }
  params.formulatedObject = filterqx("isaqbm") != "1" ? "02" : "01"
  params.orgCode = ssdept.ssdwdm
  params.orgName = ssdept.ssdwmc
  params.year = new Date().getFullYear()
  // 需要判断是单位新增还是部门新增
  if (["10", "20", "30"].includes(deptData.value.orgLevel)) {
    // 单位新增查询单位的主管领导
    getApi({ orgcode: deptData.value.orgCode.replace("XN", "") }, `/mosty-jcgl/securitychild/getZgldByOrgId`).then((res) => {
      if (res) {
        params.userid = res.id
        params.username = res.userName
        params.name = `${listQuery.year}年《${deptData.value.orgName}》安全目标/指标`
        title.value = "安全目标/指标新增"
        isEdit.value = false
        showAdd.value = true
      } else {
        ElMessage.error("未查询到单位主管领导,请先设置后在添加！")
      }
    })
  } else {
    params.userid = ""
    params.username = ""
    changeType()
    title.value = "安全目标/指标新增"
    isEdit.value = false
    showAdd.value = true
  }
}

//获取安全目标/指标详情
function getAqmbXq(id) {
  getApi({ id }, `/mosty-jcgl/safetarget/getInfo`).then((res) => {
    showAdd.value = true
    // params.formulatedObject = "02"
    params.orgCode = ssdept.ssdwdm
    params.orgName = ssdept.ssdwmc
    params.year = res.year
    params.userid = res.userIdList.toString()
    params.name = res.name
    params.files = res.files
    params.username = res.userNameList.toString()
    ruleForm.value.mbtableData = res.itemList

  })
}

//保存
const handleSave = async (fromFrs) => {
  if (!fromFrs) return
  await fromFrs.validate((valid) => {
    if (valid) {
      if (ruleForm.value) {
        loading.value = true
        params.itemList = [
          ...ruleForm.value.mbtableData
        ]
        params.year = listQuery.year
        const para = {
          ...params,
          userIdList: params.userid ? params.userid.split(",") : [],
          files: params.files ? params.files.toString() : ""
        }
        // params.userIdList = params.userid ? params.userid.split(",") : []
        // params.files = params.files ? params.files.toString() : ""
        if (title.value == "安全目标/指标新增") {
          postApi(para, "/mosty-jcgl/safetarget/addSafeTarget").then(() => {
            loading.value = false
            ElMessage.success("新增成功")
            showAdd.value = false
            getDataList()
          }).finally(() => {
            loading.value = false
          })
        } else {
          postApi(para, "/mosty-jcgl/safetarget/editSafeTarget").then(() => {
            loading.value = false
            ElMessage.success("修改成功")
            showAdd.value = false
            getDataList()
          }).finally(() => {
            loading.value = false
          })
        }
      }
    } else {
      ElMessage.error("请输入必填项")
    }
  })

}

function handleClose() {
  if(!fromFrs.value) return
  if (!isdisabled.value) {
    proxy.$modal.confirm("离开会丢失页面中修改的内容，确认离开吗？")
      .then(() => {
        showAdd.value = false
        isdisabled.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    showAdd.value = false
    isdisabled.value = false
  }

}

//新增安全目标/指标指标指向
const addNew = () => {
  editIndex.value = null
  showType.value = "0"
  titletwo.value = "安全目标/指标子项新增"
  xqData.value = {}
  // 新增的时候获取当前已经被添加过的子选项
  checkIds.value = []
  ruleForm.value.mbtableData.forEach((item) => checkIds.value.push(item.targetid))
  showAddlable.value = true
}
//修改子项目
const handlexg = (row, index) => {
  editIndex.value = index
  titletwo.value = "安全目标/指标子项修改"
  showType.value = "1"
  showAddlable.value = true
  xqData.value = { itemname: row.itemname, list: [row] }
}
// 完结子项目
const handFinish = (row, index) => {
  editIndex.value = index
  titletwo.value = "安全目标/指标子项完结"
  showType.value = "3"
  showAddlable.value = true
  xqData.value = { itemname: row.itemname, list: [row] }
}
const handlesee = (row, index) => {
  editIndex.value = index
  titletwo.value = "安全目标/指标子项详情"
  showType.value = "2"
  showAddlable.value = true
  // xqData.value = { ...row }
  xqData.value = { itemname: row.itemname, list: [row] }
}
// 控制新增弹出框的展示
const changeAddVi = (val) => {
  showAddlable.value = val
}
//接收子组件传来的值
const addDataTab = (val) => {
  
  if (editIndex.value != null) {
    ruleForm.value.mbtableData.forEach((item, index) => {
      if (val.targetid == item.targetid) {
        ruleForm.value.mbtableData[index] = val
      }
    })

  } else {
    ruleForm.value.mbtableData = [...ruleForm.value.mbtableData, ...val.list]

    // if (ruleForm.value.mbtableData.length == 0) {
    //   ruleForm.value.mbtableData.push(val)
    // } else {
    //   ruleForm.value.mbtableData = []
    //   // let flag = false
    //   // ruleForm.value.mbtableData.forEach((item) => {
    //   //     if (val.targetid == item.targetid) {
    //   //       ElMessage.warning("目标/指标子项重复,已自动移除!");
    //   //       flag = true
    //   //     }
    //   // })
    //   // if (!flag) {
    //   //   ruleForm.value.mbtableData.push(val)
    //   // }
    // }

  }
}
/** 完结关闭 */
const finish = () => {
  showAddlable.value = false
  let id = params.id
  getAqmbXq(id)
  // getDataList();
}
// 删除新增弹窗表格数据
const handledelete = (row, inds) => {
  ruleForm.value.mbtableData.forEach((item, index) => {
    if (row == item) {
      ruleForm.value.mbtableData.splice(index, 1)
    }
  })

}

//分页
const handleSizeChange = (val) => {
  listQuery.pageSize = val
  pageData.pageConfiger.pageSize = val
  getDataList()
}
const handleCurrentChange = (val) => {
  listQuery.pageCurrent = val
  pageData.pageConfiger.pageCurrent = val
  getDataList()
}
</script>

<style lang="scss" scoped>
.el-dialog__headerbtn {
  margin-top: -6px !important;
}

.el-dialog__headerbtn .el-dialog__close {
  font-size: 27px !important;
}


.xzmb_box {
  margin-top: 10px;

  > div {
    width: 100%;

    .titles {
      text-align: center;
      font-size: 18px;
      font-weight: 800;
      line-height: 35px;
    }
  }
}

.tabHeight {
  height: calc(100vh - 559px)
}

.btn {
  padding: 10px;
  float: right;
}

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