<template>
  <!--  分解主列表 -->
  <el-dialog v-model="props.decomposeWindow" title="分解责任列表" width="60%" @close="setDecomposeWindowState()">
    <MOSTY.Table :table-columns="pageData.tableColumns" :tableloading="tableloading" :tableData="pageData.tableData"
                 :tableHeight="'480px'" :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 }">
        <span class="operesee" @click="decomposeWItem(row.id)">
                    <el-icon>
                      <Finished />
                    </el-icon>分解列表</span>
        <span class="operesee" @click="viewBreakdownDetails(row.id)">
                  <el-icon>
                    <Compass />
                  </el-icon>查看分解</span>
      </template>
    </MOSTY.Table>
    <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
                 @changeSize="handleSizeChange" />
    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click='setDecomposeWindowState()'>
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
    </template>
  </el-dialog>

  <!--  分解列表-->
  <el-dialog v-model="decomposeWindow" title="分解列表" width="50%" align-center>
    <MOSTY.Table :table-columns="mbtabColumns" :tableHeight="'480px'" :tableData="decomposeItem" :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 #targetRestrictionType="{ row }">
        <span>{{ indicatorRules.get(row.targetRestrictionType) }}</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="decomposeResponsibility(scope.row)">
                <el-icon>
                  <Compass />
                </el-icon>分解</span>
      </template>
    </MOSTY.Table>
    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click='decomposeWindow = false'>
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
    </template>
  </el-dialog>

  <el-dialog v-model="decompositionDetails" title="查看分解详情" width="60%">
    <el-table
      :data="tableData"
      :tree-props="false"
      row-key="id"
      :height="'520px'"
      default-expand-all
    >
      <el-table-column prop="targetName" label="分解单位" />
      <el-table-column prop="targetValue" label="分解数值" />
      <el-table-column prop="address" label="大/小">
        <template #default="scope">
          <span>{{ indicatorRules.get(scope.row.targetRestrictionType) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click='decompositionDetails = false'>
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
    </template>
  </el-dialog>

  <!-- 分解对话框-->
  <el-dialog v-model="decomposeResponsibilityWin" title="分解责任目标" width="60%">
    <el-form style="display: block; height: 600px" ref="formRef" :model="ruleForm" label-width="220px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="分解单位">
            <el-input v-model="ruleForm.rydwmc" clearable readonly style="width:600px" disabled
                      placeholder="清选择分解单位">
              <template #append>
                <el-button @click="selectTheDecompositionDepartment()">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(_item, index) of ruleForm.list" :key="index">
        <el-col :span="12">
          <el-form-item :label="responsibleDepartment[index].orgName" :prop="'list.' + index + '.targetValue'" :rules="{
        required: true,
        message: '分解数值不能为空',
        trigger: 'blur',
      }">
            <el-input v-model="_item.targetValue" placeholder="请输入分配值" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="目标值大小">
            <el-select v-model="_item['targetRestrictionType']" placeholder="请选择指标大小">
              <el-option label="大于等于" value='0' />
              <el-option label="小于等于" value='1' />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <div style="margin: 8px 0 0 6px;">
            <el-icon @click="deleteTheSelectedDepartment(index)">
              <Delete />
            </el-icon>
          </div>
        </el-col>
        <el-col :span="24">
          <el-form-item label="控制结果：">
            <el-input v-model="_item['result']" type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="控制措施：">
            <el-input v-model="_item['measure']" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button type="primary" @click='decomposeResponsibilityWin = false'>
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
    </template>
  </el-dialog>
  <!--  分解部门选择 -->
  <DecomposeOrganization :showDdld="showDept" @closezzjg="closezzjg1"  :deptId="deptId" v-model="selectData"
                         searchType="01" :Isstrictly="false" @listdata="getSonValues1" />

</template>

<script setup>
import { defineEmits, getCurrentInstance, reactive, ref, watch, onMounted } from "vue"
import * as MOSTY from "@/components/MyComponents/index"
import { getApi, postApi } from "@/api/tobAcco_api"
import DecomposeOrganization from "@/components/MyComponents/ChooseDept/decomposeOrganization.vue"
import { getItem } from "@/utils/storage"
import { ElMessage } from "element-plus"

const { proxy } = getCurrentInstance()
const {
  D_BZ_TARGET_ITEM_JSFS,
  D_BZ_SFDB
} = proxy.$dict("D_BZ_TARGET_ITEM_JSFS", "D_BZ_SFDB")

const props = defineProps({
  // 选择的部门id
  deptCode: {
    type: String,
    default: ""
  },
  // 分解窗口
  decomposeWindow: {
    type: Boolean,
    default: false
  }
})
const rules = reactive({
  rydwmc: [{
    trigger: "blur",
    required: true,
    message: "分解单位不能为空"
  }],
  name: [{
    trigger: "blur",
    required: true,
    message: "分配值不能为空"
  }]
})
const tableData = ref([])
const emits = defineEmits(["setDecomposeWindowState"])
let decomposeWindow = ref(false)
let decompositionDetails = ref(false)
const deptId = ref()
let ruleForm = ref({
  rydwmc: "",
  list: []
})
let indicatorRules = ref(new Map([
  [null, "-"],
  ["0", "大于等于"],
  ["1", " 小于等于"]
]))
let responsibleDepartment = ref([])
const showDept = ref(false)
const selectData = ref([])
const mbtabColumns = reactive([
  {
    title: "目标/指标子项名称",
    prop: "itemname"
  },
  {
    title: "计算方式",
    prop: "targetValueType", // 2: 百分比
    slot: true
  },
  {
    title: "目标/指标",
    prop: "target",
    slot: true
  },
  {
    title: "目标/指标（大/小）",
    prop: "targetRestrictionType",
    slot: true
  },
  {
    title: "完成度",
    prop: "realTarget",
    slot: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
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: []
})
let decomposeResponsibilityWin = ref(false)
let formRef = ref(null)
let decomposeItem = ref([])
let decomposeObjects = ref({})
const tableloading = ref(false)
let decomposeId = ref("")
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  deptCode: "",
  formulatedObject: '01',
  year: new Date().getFullYear()
})

/**
 * 提交分解
 * @param formEl
 */
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      let totalDecompositionValue = 0
      // dd计算分解总数
      // 只在数字或者百分比类型下校验分解数值
      if (decomposeObjects.value?.targetValueType === "1" || decomposeObjects.value?.targetValueType === "2") {
        for (let i = 0; i < ruleForm.value.list.length; i++) {
          totalDecompositionValue += Number(ruleForm.value.list[i].targetValue)
        }
        // 分解指标是否符合要求
        if (decomposeObjects.value?.targetRestrictionType === "0" && !(totalDecompositionValue >= Number(decomposeObjects.value.target))) {
          ElMessage.error("分解值的总数必须大于等于" + decomposeObjects.value.target)
          return
        }
        if (decomposeObjects.value?.targetRestrictionType === "1" && !(totalDecompositionValue <= Number(decomposeObjects.value.target))) {
          ElMessage.error("分解值的总数必须小于等于" + decomposeObjects.value.target)
          return
        }
        let obj = {
          subsetDtos: ruleForm.value.list,
          safeTargetId: decomposeId.value,
          safeTargetItemId: decomposeObjects.value.targetid
        }
        postApi(obj, "/mosty-jcgl/safetarget/breakDownSafeTarget").then(res => {
          ElMessage.success("操作成功")
          decomposeResponsibilityWin.value = false
        })
      }
    } else {
      ElMessage.error("必填项不能为空")
    }
  })
}

/**
 * 删除选择的部门
 * @param index
 */
const deleteTheSelectedDepartment = (index) => {
  ruleForm.value.list.splice(index, 1)
  ruleForm.value.rydwmc = ''
  ruleForm.value.list.forEach(item => {
    ruleForm.value.rydwmc += item.targetName
  })
}

/**
 * 分解详情查看
 * @param id
 */
const viewBreakdownDetails = (id) => {
  getApi({ safeId: id }, "/mosty-jcgl/safetarget/getBreakDownTree").then(res => {
    decompositionDetails.value = true
    let data = []
    res.forEach(item => {
      for (let i = 0; i < item.child.length; i++) {
        data.push(item.child[i])
      }
    })
    tableData.value = data
  })
}

/**
 * 选择分解部门
 */
const selectTheDecompositionDepartment = () => {
  showDept.value = true
  ruleForm.value = {
    rydwmc: "",
    list: []
  }
}

/**
 * 获取部门信息
 * @param val
 * @returns {Promise<void>}
 */
const getSonValues1 = async (val) => {
  responsibleDepartment.value = val
  val.forEach(item => {
    ruleForm.value.rydwmc += item.orgName + "/"
    ruleForm.value.list.push({
      targetValue: "",
      targetid: item.id,
      targetName: item.orgName,
      result: "",
      measure: "",
      targetRestrictionType: '1'
    })
  })
}

/**
 * 选择组织单位时触发
 * @param val
 */
const closezzjg1 = (val) => {
  showDept.value = val
}

/**
 * 获取分解子选项列表
 */
const getDataList = () => {
  tableloading.value = true
  listQuery.deptCode = getItem("deptId").ssdwid
  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
  })
}

/**
 * 关闭分解窗口
 */
const setDecomposeWindowState = () => emits("setDecomposeWindowState", false)

/**
 * 页码发生变化触发
 * @param val
 */
const handleCurrentChange = (val) => {
  listQuery.pageCurrent = val
  pageData.pageConfiger.pageCurrent = val
  getDataList()
}

/**
 * 分页发生变化触发该函数
 * @param val
 */
const handleSizeChange = (val) => {
  listQuery.pageSize = val
  pageData.pageConfiger.pageSize = val
  getDataList()
}

/**
 * 监听分解总列表的变化获取分解列表
 */
watch(
  () => props.deptCode,
  (val) => {
    // listQuery.deptCode = val
    console.log(listQuery)
    // getDataList()
  },
  {
    deep: true,
    immediate: true
  }
)

/**
 * 打开分解窗口
 */
const decomposeResponsibility = (row) => {
  if (row.target < "0") {
    ElMessage.error("目标值小于0无法分解")
    return
  }
  getApi({ targetId: row.targetid }, "/mosty-jcgl/safetarget/getBreakDownList").then(res => {
    console.log(res)
    ruleForm.value = {
      rydwmc: "",
      list: []
    }
    responsibleDepartment.value = []
    if (res.length > 0) {
      res.forEach(item => {
        ruleForm.value.rydwmc += "/" + item.targetName
        item.orgName = item.targetName
        ruleForm.value.list.push(item)
        responsibleDepartment.value.push(item)
      })
      console.log(ruleForm.value)
    }
    decomposeObjects.value = row
    decomposeResponsibilityWin.value = true
  })
}

/**
 * 查看分解列表
 * @param id
 * @returns {Promise<void>}
 */
const decomposeWItem = (id) => {
  decomposeId.value = id
  decomposeWindow.value = true
  getApi({ id }, `/mosty-jcgl/safetarget/getInfo`).then((res) => {
    decomposeItem.value = res?.itemList
    console.log(res, "分解详情")
  })
}

onMounted(() => {
  getDataList()
})

</script>


<style scoped lang="scss">

</style>
