<template>
  <div>
    <el-dialog v-model="props.addShow" :title=props.title width="1000px" :before-close="handleClose">
      <!-- 培训计划新增或修改 -->
      <div class="config">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :disabled="props.showType == '2'"
                 style="width: 100%;display: block;" :inline="true" label-width="100px">
          <el-form-item label="子项：" prop="itemname">
            <el-input v-model="ruleForm.itemname" clearable disabled style="width: 820px;">
              <template #append>
                <el-button :disabled="props.showType == 3" @click="choose()">选择</el-button>
              </template>
            </el-input>
          </el-form-item>

          <div style="border-top: 1px solid #c8c5c5; padding-top: 20px" v-for="(_item, index) of ruleForm.list" :key="index">
            <el-form-item label="目标名称：">
              <el-input v-model="_item.itemname" clearable disabled style="width: 820px;"/>
            </el-form-item>
            <el-form-item label="计算方式：" :prop="'list.' + index + '.targetValueType'">
              <el-select v-model="_item.targetValueType" clearable disabled style="width:185px;">
                <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="'list.' + index + '.target'">
              <el-input v-if="_item.targetValueType != '3'" v-model="_item.target" maxlength=10
                        type="number" :disabled="props.showType == 3">
                <template #append v-if="_item.targetValueType == '2'">%</template>
              </el-input>
              <el-select v-else v-model="_item.target" disabled clearable>
                <el-option v-for="item in D_BZ_SFDB" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="_item.targetValueType === '1' || _item.targetValueType === '2'" label="目标值大小:"
                          :prop="'list.' + index + '.targetRestrictionType'">
              <el-select v-model="_item.targetRestrictionType"  :disabled="props.showType == 3" placeholder="请选择指标大小">
                <el-option label="大于等于" value='0' />
                <el-option label="小于等于" value='1' />
              </el-select>
            </el-form-item>
            <el-form-item v-else label="目标值大小:"
                          :prop="'list.' + index + '.targetRestrictionType'">
              <el-select v-model="_item.targetRestrictionType"  :disabled="_item.targetValueType == 3" placeholder="请选择指标大小">
                <el-option label="达标" value='3' />
              </el-select>
            </el-form-item>
            <el-form-item v-if="props.showType == 3" label="完成度:" prop="realTarget">
              <el-input v-if="ruleForm.targetValueType != '3'" v-model="_item.realTarget" maxlength=10
                        type="number" style="width:185px;">
                <template #append v-if="ruleForm.targetValueType == '2'">%</template>
              </el-input>
              <el-select v-else v-model="_item.realTarget" disabled clearable style="width: 185px;">
                <el-option v-for="item in D_BZ_SFDB" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="控制措施：">
              <el-input v-model="_item.measure" :disabled="props.showType == 3" type="textarea"
                        style="width: 820px" />
            </el-form-item>
            <el-form-item label="备注：">
              <el-input v-model="_item.bz" :disabled="props.showType == 3" type="textarea"
                        style="width: 820px" />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template #footer>
                <span class="dialog-footer">

                    <el-button type="primary" v-if="props.showType != '2'" :loading="loading"
                               @click="handleSave(ruleFormRef)">
                        <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>
      <!-- 目标指标选择 -->
      <TargetList :targetShow="targetShow" :checkIds="props.checkIds" :deptCode="props.deptCode" @close="closeTarget"
                  :dict="{ D_BZ_TARGET_ITEM_JSFS, D_BZ_SF, D_BZ_SFDB }" @change="changeTargetShow">
      </TargetList>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入
import { ref, defineProps, defineEmits, reactive, getCurrentInstance, onMounted, watch } from "vue"
import TargetList from "./targetList.vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { ElMessage } from "element-plus"

const { proxy } = getCurrentInstance()
const {
  D_BZ_TARGET_ITEM_JSFS,
  D_BZ_SF,
  D_BZ_SFDB
} = proxy.$dict("D_BZ_TARGET_ITEM_JSFS", "D_BZ_SF", "D_BZ_SFDB")
const loading = ref(false) //新增保存按钮截流
const ruleFormRef = ref()
//表单数据
const ruleForm = ref({
  list:[]
})
let selectPersonnelData = ref([])
const targetShow = ref(false)
const emits = defineEmits(["changeAddVi", "addData", "finish"])
const props = defineProps({
  checkIds:{
    type: Array,
    default: () => []
  },
  addShow: {
    type: Boolean,
    default: false
  },
  deptCode: String,
  /** 展示类型 1.编辑 2.详情 3.完成 */
  showType: String,
  title: String,
  xqData: {
    type: Object,
    default: {}
  }
})
//规则校验
const rules = reactive({
  targetRestrictionType: [
    {
      required: true,
      message: "目标指标大小不能为空",
      trigger: "blur"
    }
  ],
  type: [{
    required: true,
    message: "目标/指标不能为空",
    trigger: "blur"
  }],
  itemname: [{
    required: true,
    message: "子项名称不能为空",
    trigger: "blur"
  }],
  targetValueType: [{
    trigger: "blur",
    required: true,
    message: "目标指标计算方式不能为空"
  }],
  target: [
    {
      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"
    }
  ],
  realTarget: [
    {
      required: true,
      message: "请输入完成度",
      trigger: "blur"
    },
    {
      validator: (rule, value, callback) => {
        if (props.showType != 3) 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"
    }]
})

watch(
  () => props.addShow,
  (val) => {
    if (!val) {
      ruleForm.value = {}
    } else {
      ruleForm.value = props.xqData
    }
  }
)
// 关闭选择
const changeTargetShow = (val) => {
  targetShow.value = false
  selectPersonnelData.value = val
  ruleForm.value.list = []
  ruleForm.value.itemname = ''
  val.forEach((item) => {
    ruleForm.value.itemname += item.targetName + '/'
    ruleForm.value.list.push({
      itemname: item.targetName,
      bz:"",
      measure:"",
      target:item.targetValue.replace("%", ""),
      targetRestrictionType: item.targetValueType === '1' ? '1' : item.targetValueType === '2' ? '0' : '3',
      targetValueType:item.targetValueType
    })
  })

  // ruleForm.value.itemname = val.targetName
  // ruleForm.value.targetValueType = val.targetValueType
  // ruleForm.value.target = val.targetValue.replace("%", "")
  ruleFormRef.value.clearValidate()
}

// 选择框
const choose = () => {
  targetShow.value = true
}
// 关闭
const handleClose = () => {
  if (props.showType != "2") {
    proxy.$modal.confirm("离开会丢失页面中修改的内容，确认离开吗？")
      .then(() => {
        emits("changeAddVi", false)
      })
      .catch(() => {
        // catch error
      })
  } else {
    emits("changeAddVi", false)
  }

}
// 关闭target列表
const closeTarget = (val) => {
  targetShow.value = false
}
/** 完结保存 */
const finishSave = () => {
  let params = ruleForm.value
  params.id = params.targetid
  delete params.targetid
  postApi(params, "/mosty-jcgl/safetarget/completeItem").then(res => {
    if (!res) return
    ElMessage.success("完结成功!")
    emits("finish", params.id)
  })
}
// 保存
const handleSave = (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      if (props.showType === "3") {
        finishSave()
      } else {
        loading.value = true
        emits("addData", ruleForm.value)
        emits("changeAddVi", false)
        loading.value = false

      }
    }
  })
}

</script>

<style scoped>
:deep(.el-dialog__body){
  height: 600px;
  overflow-y: scroll;
}
</style>
