<template>
  <div class="dialog" v-if="dialogForm">
    <div class="head_box">
      <span class="title">战术研判{{ title }} </span>
      <div>
        <el-button type="primary" size="small" v-if="title != '详情'" :loading="loading" @click="submit">保存</el-button>
        <el-button size="small" @click="close">关闭</el-button>
      </div>
    </div>
    <div style="padding-bottom: 40px;" class="form_cnt">
      <FormMessage v-model="listQuery" :formList="formData" ref="elform" :rules="rules">
        <template #bmList>
          <div class="table-box">
            <el-table :data="tableList" border style="width: 100%">
              <el-table-column prop="ypbmmc" label="部门" width="150" align="center" />
              <el-table-column label="研判素材" width="280" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.scyq" :disabled="!isShiQingBaoZhongXin" placeholder="请输入研判素材" />
                </template>
              </el-table-column>
              <el-table-column label="附件" width="200" align="center">
                <template #default="{ row }">
                  <UploadFile v-model="row.fj" :disabled="!isShiQingBaoZhongXin" :limit="1" :isImg="false"
                    :isAll="true" />
                </template>
              </el-table-column>
              <el-table-column prop="wcqk" label="完成状态" width="120" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.wcqk === '02' ? 'success' : 'warning'">
                    {{ row.wcqk == '01' ? '准备中' : '已完成' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" align="center">
                <template #default="{ row }">
                  <el-button type="text" size="small" @click="updateStatus(row)" :disabled="updateDis(row)">
                    修改状态
                  </el-button>
                  <el-button type="text" size="small" @click="submitMaterial(row)" :disabled="updateDis(row)">
                    提交素材
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </FormMessage>
    </div>
    <!-- 底部按钮 -->
    <div class="bottom-actions" v-if="title !== '新增' && listQuery.id">
      <el-button type="primary" size="small" @click="sendNotice" :loading="noticeLoading">下发通知</el-button>
      <el-button type="success" size="small" @click="confirmJudgment" :loading="confirmLoading">确认研判</el-button>
    </div>
  </div>

  <!-- 修改状态弹框 -->
  <div class="dialog" v-if="statusDialog">
    <div class="head_box">
      <span class="title">修改状态</span>
      <div>
        <el-button type="primary" size="small" :loading="statusLoading" @click="submitStatus">保存</el-button>
        <el-button size="small" @click="closeStatusDialog">关闭</el-button>
      </div>
    </div>
    <div class="form_cnt">
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="附件">
          <UploadFile v-model="statusForm.fj" :limit="2" :isImg="false" :isAll="true" />
        </el-form-item>
      </el-form>
    </div>
  </div>

  <!-- 提交素材弹框 -->
  <div class="dialog" v-if="materialDialog">
    <div class="head_box">
      <span class="title">提交素材</span>
      <div>
        <el-button type="primary" size="small" :loading="materialLoading" @click="submitMaterialAction">保存</el-button>
        <el-button size="small" @click="closeMaterialDialog">关闭</el-button>
      </div>
    </div>
    <div class="form_cnt">
      <el-form :model="materialForm" label-width="80px">
        <el-form-item label="附件">
          <UploadFile v-model="materialForm.fj" :limit="2" :isImg="false" :isAll="true" />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import FormMessage from "@/components/aboutTable/FormMessage.vue";
import UploadFile from "@/components/MyComponents/Upload/index.vue";
// import ChooseUser from "@/components/ChooseList/ChooseUser/index.vue"
import { ref, defineExpose, reactive, defineEmits, getCurrentInstance, watch, computed } from "vue";
import { sjzlAddEntity, sjzlEditEntity, sjzlGetInfo, sjzlPerfectlnfo, sjzlFstz, sjzlQryp, sjzlPerfectSorce } from '@//api/yj.js'
import { getItem } from '@//utils/storage.js'

const emit = defineEmits(["updateDate", "getList"]);
const props = defineProps({
  dict: Object
});
const imgMsg = ref([])
const { proxy } = getCurrentInstance();
const dialogForm = ref(false); //弹窗
const formData = ref([

]);
const { deptBizType, deptLevel, deptCode } = getItem('deptId')[0]
/** 登录人 */
const sfzh = getItem('idEntityCard')
/** 是否市情报指挥中心 */
const isShiQingBaoZhongXin = computed(() => {
  const Jb = deptLevel[0] == '2' ? '01' : deptLevel[0] == '3' ? '02' : '03'
  return deptBizType == '23' && Jb == '01'
})
const listQuery = ref({}); //表单
const loading = ref(false);
const elform = ref();
const title = ref("");
const tableList = ref([])
// const detailObj = ref({})
const statusDialog = ref(false) // 修改状态弹框
const statusLoading = ref(false)
const statusForm = ref({ fj: [] }) // 修改状态表单
const currentRow = ref({}) // 当前操作的行

// 提交素材相关
const materialDialog = ref(false) // 提交素材弹框
const materialLoading = ref(false)
const materialForm = ref({ fj: [] }) // 提交素材表单
const materialRow = ref({}) // 当前操作的行

/** 外面行数据 */
const outRow = ref({})
const noticeLoading = ref(false) // 下发通知加载状态
const confirmLoading = ref(false) // 确认研判加载状态

const rules = reactive({
  // 可以在这里添加表单验证规则
});
watch(() => props.dict, (val) => {
  if (val) {
    formData.value = [
      { label: "研判议题", prop: "ypyt", type: "input", width: '48%' },
      { label: "研判时间", prop: "ypsj", type: "datetime", width: '48%' },
      { label: "报告类型", prop: "bglx", type: "radio", options: props.dict.D_BZ_YPLX, width: '48%' },
      { label: "研判方式", prop: "ypfs", type: "radio", options: props.dict.D_BZ_YPFS, width: '48%' },
      { label: "参与研判部门", prop: "jsdxBmDm", type: "department", multiple: true, depMc: 'jsdxBmMc', width: '48%' },
      { label: "研判要求", prop: "ypyq", type: "textarea", width: '100%' },
      { label: "列表", prop: "bmList", type: "slot", width: '100%' },
    ]
  }
})
/** 是否修改禁用 */
function updateDis(row) {
  /** 无id 禁用 */
  if (!listQuery.value.id) return true
  /** 是否创建人 */
  const iscjr = !row.cjrsfzh || row?.cjrsfzh == deptCode
  /** 是否完成 */
  const isFinish = row.wcqk === '02'
  return isShiQingBaoZhongXin.value || !iscjr || isFinish
}
function getFjArr(fj) {
  if (typeof fj !== 'string' || !fj) return []
  let fjArr = []
  try {
    fjArr = JSON.parse(fj)
  } catch (error) {

  }
  return fjArr
}
watch(() => listQuery.value.jsdxBmDm, (val) => {
  /** @type {Array<{ypbmdm: string, ypbmmc: string, scyq: string, fj: Array, wcqk: string}>} 参与研判部门数据数组 */
  const arr = Array.isArray(val) ? val : []
  const cyypList = Array.isArray(listQuery.value.cyypList) ? listQuery.value.cyypList : []

  tableList.value = arr.map((item, i) => {
    /** 找原来的对象 */
    const curr = cyypList.find(item2 => item2.ypbmdm == item) || {}
    /** 是否是新增 */
    const isAddForm = !listQuery.value.id
    return {
      // id: null,
      // sjzlid: null, // 研判战术研判ID
      /** 部门代码 */
      ypbmdm: item,
      ypbmmc: listQuery.value.jsdxBmMc[i],
      /** 素材要求 */
      scyq: isAddForm ? '' : curr.scyq,
      fj: isAddForm ? [] : getFjArr(curr.fj),
      /** 完成情况（01 准备中、02 已完成）*/
      wcqk: isAddForm ? '01' : curr.wcqk || '01'
    }
  })
})
// 初始化数据
const init = (type, row, wjlb) => {
  dialogForm.value = true;
  title.value = type == "add" ? "新增" : type == "edit" ? "编辑" : "详情";
  outRow.value = row || {}
  if (row) { getDataById(row.id) }
};
// 根据id查询详情
const getDataById = (id) => {
  sjzlGetInfo(id).then((res) => {
    listQuery.value = res || {};
    const cyypList = Array.isArray(res.cyypList) ? res.cyypList : []
    listQuery.value.jsdxBmDm = cyypList.map(item => {
      return item.ypbmdm
    })
    listQuery.value.jsdxBmMc = cyypList.map(item => {
      return item.ypbmmc
    })
  });
};
function getFjString(arr) {
  arr = Array.isArray(arr) ? arr : []
  return JSON.stringify(arr)
}
/**获取下发部门数据 */
const getXfbmList = () => {
  const cyypList = Array.isArray(listQuery.value.cyypList) ? listQuery.value.cyypList : []

  return tableList.value.map((item, i) => {

    /** 找原来的对象 */
    const curr = cyypList.find(item => item.ypbmdm == item.ypbmdm) || {}
    return {
      id: curr.id || null,
      sjzlid: curr.sjzlid || null, // 研判战术研判ID
      ypbmdm: item.ypbmdm,
      ypbmmc: listQuery.value.jsdxBmMc[i],
      /** 素材要求 */
      scyq: item.scyq,
      fj: getFjString(item.fj),
      /** 完成情况（01 准备中、02 已完成）*/
      wcqk: item.wcqk
    }

  })
}
// 提交
const submit = () => {
  elform.value.submit(async (data) => {
    const xfbmList = getXfbmList()
    let params = {
      ...listQuery.value,
      cyypList: xfbmList,
      // cyypList: listQuery.value.jsdxBmDm.map((item, index) => {
      //   return {
      //     ypbmdm: item,
      //     ypbmmc: listQuery.value.jsdxBmMc[index],
      //     ypcylx: '01'
      //   }
      // })
    };
    try {
      loading.value = true;
      let res
      if (title.value == "新增") {
        res = await sjzlAddEntity(params)
      } else {
        res = await sjzlEditEntity(params)
      }
      if (res && res > 0) {
        loading.value = false;
        proxy.$message({ type: "success", message: title.value + "成功" });
        emit("getList");
        close();
      }
      loading.value = false;

    } catch (error) {

      loading.value = false;
    }
  });
};

// const chooseUserVisible = ref()
// const roleIds = ref([])
// const userList = ref([])
// const handleUserSelected = (val) => {
//   userList.value = val
//   listQuery.value.jsrxm = val.map(item => item.userName).join(',')
// }
// 修改状态
const updateStatus = (row) => {
  const cyypList = Array.isArray(listQuery.value.cyypList) ? listQuery.value.cyypList : []
  /** 找原来的对象 */
  const curr = cyypList.find(item2 => item2.ypbmdm == row.ypbmdm) || {}
  currentRow.value = { ...curr, row }
  statusForm.value = { fj: [] }
  statusDialog.value = true
};

// 提交修改状态
const submitStatus = async () => {
  try {
    statusLoading.value = true
    const params = {
      id: currentRow.value.id,
      fj: statusForm.value.fj?.length > 0 ? getFjString(statusForm.value.fj) : '',
      wcqk: '02'
    }

    const res = await sjzlPerfectlnfo(params)
    if (res && res > 0) {
      proxy.$message({ type: "success", message: "修改成功" })
      // 更新本地状态
      currentRow.value.wcqk = '02'

      closeStatusDialog()
      if (outRow.value.id) { getDataById(outRow.value.id) }
    }
  } catch (error) {

  } finally {
    statusLoading.value = false
  }
}

// 关闭修改状态弹框
const closeStatusDialog = () => {
  statusDialog.value = false
  statusForm.value = { fj: [] }
  statusLoading.value = false
}

// 提交素材
const submitMaterial = (row) => {
  const cyypList = Array.isArray(listQuery.value.cyypList) ? listQuery.value.cyypList : []
  /** 找原来的对象 */
  const curr = cyypList.find(item2 => item2.ypbmdm == row.ypbmdm) || {}
  materialRow.value = { ...curr, row }
  materialForm.value = { fj: [] }
  materialDialog.value = true
}

// 提交素材操作
const submitMaterialAction = async () => {
  try {
    materialLoading.value = true
    const params = {
      id: materialRow.value.id,
      fj: materialForm.value.fj?.length > 0 ? getFjString(materialForm.value.fj) : '',
    }

    const res = await sjzlPerfectSorce(params)
    proxy.$message({ type: "success", message: "提交素材成功" })

    closeMaterialDialog()
    if (outRow.value.id) { getDataById(outRow.value.id) }
  } catch (error) {
    console.log(error)
  } finally {
    materialLoading.value = false
  }
}

// 关闭提交素材弹框
const closeMaterialDialog = () => {
  materialDialog.value = false
  materialForm.value = { fj: [] }
  materialLoading.value = false
}

// 下发通知
const sendNotice = () => {
  proxy.$confirm('确认下发通知？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      noticeLoading.value = true;
      const res = await sjzlFstz(listQuery.value.id);
      proxy.$message({ type: "success", message: "下发通知成功" });
      close();
    } catch (error) {
      console.log(error);
    } finally {
      noticeLoading.value = false;
    }
  });
};

// 确认研判
const confirmJudgment = () => {

  proxy.$confirm('确认研判完成？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      confirmLoading.value = true;
      const res = await sjzlQryp(listQuery.value.id);
      proxy.$message({ type: "success", message: "确认研判成功" });
      close();
    } catch (error) {
      console.log(error);
    } finally {
      confirmLoading.value = false;
    }
  });
};

// 关闭
const close = () => {
  listQuery.value = {};
  dialogForm.value = false;
  loading.value = false;
};

defineExpose({ init });
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

::v-deep .form-item-box {
  width: 100% !important;
}

.bottom-actions {
  position: absolute;
  bottom: 0;
  left: 50%;

  display: flex;
  justify-content: center;
  gap: 10px;
  width: 100%;
  transform: translateX(-50%);
  padding: 10px 20px;

  border-radius: 4px;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  // z-index: 1000;
}
</style>
