<template>
  <div class="dialog" v-if="dialogForm">
    <div class="head_box">
      <span class="title">布控对象</span>
      <div>
        <el-button size="small" type="primary" v-if="!disabled" :loading="loading" @click="submit">保存</el-button>
        <el-button size="small" @click="close">关闭</el-button>
      </div>
    </div>
    <div class="flex">
      <div :class="dataOrge.gzlid?'ww80':'ww100'">
        <div class="form_cnt">
          <el-form :model="listQuery" :rules="rules" :disabled="disabled" ref="elform" inline :label-width="100"
            label-position="left">
            <div class="smallTitle">布控信息</div>
            <!-- <el-form-item prop="bkBt" label="布控标题">
          <MOSTY.Other v-model="listQuery.bkBt" placeholder="请输入布控标题" clearable />
        </el-form-item> -->
            <el-form-item prop="bkDx" label="布控对象">
              <MOSTY.Select v-model="listQuery.bkDx" @change="shangeDx" :dictEnum="props.dic.D_GS_BK_DX"
                placeholder="请选择布控对象" clearable />
            </el-form-item>
            <div class="ww100 mt10 mb10">
              <el-button type="primary" @click="handleAddPeo" v-if="!disabled">
                <el-icon style="vertical-align: middle">
                  <CirclePlus />
                </el-icon>
                <span style="vertical-align: middle">新增</span>
              </el-button>
            </div>
            <div class="relative ww100">
              <MyTable :tableData="listQuery.bkdxList" :tableColumn="tableDate.tableColumn"
                :tableHeight="tableDate.tableHeight" :key="tableDate.keyCount" :tableConfiger="tableDate.tableConfiger"
                :controlsWidth="tableDate.controlsWidth">
                <template #fjZp="{ row }">
                  <el-image :src="row.fjZp"></el-image>
                </template>
                <template #yjdj="{ row }">
                  <DictTag :tag="false" :value="row.yjdj" :options="props.dic.D_GS_ZDR_YJDJ" />
                </template>
                <template #yjbq="{ row }">
                  <DictTag :tag="false" :value="row.yjbq" :options="props.dic.BD_BK_CLYJBQ" />
                </template>
                <template #ryXb="{ row }">
                  <DictTag :tag="false" :value="row.ryXb" :options="props.dic.D_BZ_XB" />
                </template>
                <template #bqList="{ row }">
                  <span v-if="row.bqList">
                    <span v-for="(it, idx) in row.bqList" :key="idx"> {{ it.bqMc }}、</span>
                  </span>
                </template>
                <!-- 操作 -->
                <template #controls="{ row }">
                  <el-link type="primary">查看档案</el-link>
                  <el-link type="danger" @click="deleteRow(row)">删除</el-link>
                </template>
              </MyTable>
            </div>

            <div class="smallTitle">布控范围</div>
            <div class="ww100 relative mb10"
              style="height: 250px;border: 1px solid #dcdfe6;border-radius: 4px;overflow: hidden;">
              <div class="absolute mapSearch flex">
                <MOSTY.Select v-model="listQuery.bkqyList" filterable multiple :dictEnum="bkqyArr" style="width:350px"
                  placeholder="请选择布控范围" clearable />
              </div>
              <GdMap></GdMap>
            </div>
            <!-- <el-form-item prop="bkBt" label="布控要素" style="width: 100%;">
          <div class="flex align-center">
            <el-button @click="listQuery.bkYz = it.dm" :type="listQuery.bkYz == it.dm ? 'primary' : ''"
              v-for="it in props.dic.D_GS_BK_BKYS" :key="it">{{ it.zdmc }}</el-button>
          </div>
        </el-form-item> -->
            <div style="width: 100%;" class="mt25">
              <el-form-item prop="bkSjKs" label="布控开始时间" label-width="120px">
                <MOSTY.Date v-model="listQuery.bkSjKs" type="datetime" format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择布控开始时间" clearable />
              </el-form-item>
              <el-form-item prop="bkSjJs" label="布控结束时间" label-width="120px">
                <MOSTY.Date v-model="listQuery.bkSjJs" type="datetime" format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择布控结束时间" clearable />
              </el-form-item>
            </div>
            <div style="width: 100%;" class="mt25">
              <el-form-item prop="czYq" label="处置要求">
                <MOSTY.Select v-model="listQuery.czYq" :dictEnum="props.dic.D_GS_BK_CZYQ" placeholder="请选择处置要求"
                  clearable />
              </el-form-item>
              <el-form-item prop="bkDj" label="布控等级">
                <MOSTY.Select v-model="listQuery.bkDj" :dictEnum="props.dic.D_GS_BK_DJ" placeholder="请选择布控级别"
                  clearable />
              </el-form-item>
            </div>
            <div style="width: 100%;" class="mt10">
              <el-form-item prop="bkSy" label="布控事由" style="width: 100%;">
                <MOSTY.Other v-model="listQuery.bkSy" placeholder="请输入布控事由" type="textarea" style="width: 100%;"
                  clearable />
              </el-form-item>
            </div>
            <div style="width: 100%;" class="mt10">
              <el-form-item prop="bkfj" label="上传附件" style="width: 100%;">
                <div>
                  <MOSTY.Upload :showBtn="true" :limit="10" :isImg="false" :isAll="true" v-model="listQuery.bkfj" />
                  <div>支持png、jpg、pdf文件上传</div>
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div class="ww20" v-if="dataOrge.gzlid">
        <!-- <div class="smallTitle">审批信息</div>
        <div class="ww100">
          <el-steps :active="listQuery.wccz" space="500" finish-status="success" direction="vertical" status=''>
            <el-step :title="item.eventType == '0' ? '发起申请' : item.eventType == '1' ? '审批结束' : item.nodeName"
              v-for="(item, index) in workflow" :key="index">
              <template #description>
                <div class="ww100 mt10 mb20 nodeBox" v-if="item.eventType == '0'||item.eventType == '1'">
                  <div class="nodeorgNameTg">{{ item.log.userData.orgname }}</div>
                  <div class="flex just-between nameTag">
                    <div>{{ item.log.userName }}</div>
                    <div class="fontColor">{{ item.eventType == '0' ? '发起' : '结束' }}</div>
                  </div>
                  <div>{{ item.log.xtLrsj }}</div>
                </div>
                <div v-else class="ww100 mt10 mb20 nodeBox">
                  <div  :class="item.taskStatus=='2'?'nodeorgNameTg':'nodeorgNameDd'">{{ item.orgNameData.orgname }}</div>
                  <div v-for="(items, indexs) in item.log" :key="indexs">
                    <div class="flex just-between nameTag"  >
                      <div>{{ items.userName }}</div>
                      <div  :class="item.taskStatus=='2'?'fontColor':'fontColorDd'">审批中</div>
                    </div>
                    <div>{{ items.xtLrsj }}</div>
                  </div>

                </div>
              </template>
            </el-step>

          </el-steps>
        </div> -->
        <ApprovalEcho ref="approvalEcho"/>
      </div>
    </div>

  </div>
  <!-- 选择布控人员 -->
  <BkryDialod :modelValue="chooseVisible_RY" @update:modelValue="chooseVisible_RY = $event" @choosed="choosed"
    @choosedAdd="choosedAdd" :roleIds="roleIds" />
  <!-- 选择车辆布控 -->
  <BkclDialod :modelValue="chooseVisible_CL" @update:modelValue="chooseVisible_CL = $event" @choosed="choosed"
    @choosedAdd="choosedAdd" :roleIds="roleIds" />
  <!-- 选择布控群体 -->
  <BkqtDialod :modelValue="chooseVisible_QT" @update:modelValue="chooseVisible_QT = $event" @choosed="choosed"
    :roleIds="roleIds" />
  <BksfzDialod :modelValue="chooseVisible_SFZ" @update:modelValue="chooseVisible_SFZ = $event" @choosed="choosed"
    :roleIds="roleIds" :bkDx="listQuery.bkDx" @choosedAdd="choosedAdd" />
</template>

<script setup>
import { getItem } from "@/utils/storage";
import BkryDialod from '@/components/ChooseList/ChooseZdr/index.vue';
import BkqtDialod from '@/components/ChooseList/ChooseQt/index.vue';
import BkclDialod from '@/components/ChooseList/ChooseCl/index.vue';
import BksfzDialod from './dolog/sfzLog.vue';
import GdMap from "@/components/GdMap/index.vue";
import * as MOSTY from "@/components/MyComponents/index";
import MyTable from "@/components/aboutTable/MyTable.vue";
import { qcckGet, qcckPost } from "@/api/qcckApi.js";
import { tableColumnList,Zd } from '@/views/backOfficeSystem/ApprovalInformation/tableRow.js'

import { ref, defineExpose, reactive, defineEmits, getCurrentInstance, nextTick, watch } from "vue";
import { queryProcessNode, queryProcessNodeLog, queryProcess } from '@/api/spl'
import ApprovalEcho from "@/components/flowPath/ApprovalEcho.vue";
const emit = defineEmits(["change"]);
const props = defineProps({
  dic: Object
});
const elform = ref()
const roleIds = ref([]); //角色ID
const chooseVisible_RY = ref(false); //选择布控人员弹窗
const chooseVisible_QT = ref(false); //选择布控群体弹窗
const chooseVisible_CL = ref(false)
const bkqyArr = ref([]); //布控区域
const { proxy } = getCurrentInstance();
const dialogForm = ref(false); //弹窗
const loading = ref(false)
const addPerson = ref([]) //单独新增的数据
const listQuery = ref({
  bkYz: '01',
  bkdxList: [],
}); //表单数据
const rules = reactive({
  bkBt: [{ required: true, message: "请输入布控标题", trigger: "blur" }],
  bkDx: [{ required: true, message: "请选择布控对象", trigger: "change" }],
  bkSjKs: [{ required: true, message: "请选择布控开始时间", trigger: "change" }],
  bkSjJs: [{ required: true, message: "请选择布控结束时间", trigger: "change" }],
  czJsdwdm: [{ required: true, message: "请选择处置接收单位", trigger: "change" }],
  bkshrSsbmdm: [{ required: true, message: "请选择审核部门", trigger: "change" }],
  bksprSsbmdm: [{ required: true, message: "请选择审批部门", trigger: "change" }],
})
let tableDate = reactive({
  keyCount: 0,
  tableConfiger: {
    rowHieght: 61,
    showSelectType: "null",
    loading: false
  },
  total: 0,
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1
  }, //分页
  controlsWidth: 200, //操作栏宽度
  tableColumn: [
    { label: "照片", prop: "fjZp", showSolt: true },
    { label: "姓名", prop: "ryXm" },
    { label: "性别", prop: "ryXb", showSolt: true },
    { label: "身份证号", prop: "rySfzh" },
    { label: "户籍地", prop: "ryHjd" },
    { label: "现居住地址", prop: "ryXjd" },
    { label: "手机号", prop: "rySjhm" },
    { label: "虚拟身份", prop: "qtXnsf" },
    { label: "车牌号", prop: "clCph" },
    { label: "车辆识别代码", prop: "clCjh" },
    { label: "特征描述", prop: "qtTzms" },
    { label: "标签", prop: "bqList", showSolt: true, showOverflowTooltip: true }
  ]
});
const title = ref('')
const disabled = ref(false)
// 初始化数据
const init = (type, row) => {
  listQuery.value.bkfj = [];
  if (type == 'add') {
    tableDate.tableConfiger.haveControls = true;
    disabled.value = false;
    listQuery.value.bkfqrXm = getItem("USERNAME");
  console.log(getItem("USERNAME"));

    listQuery.value.bkfqrSfzh = getItem("idEntityCard");
    console.log( getItem("USERID"));
    console.log( getItem("idEntityCard"));
    listQuery.value.bkfqrSsbmmc = getItem("deptId")[0].deptName;;
    listQuery.value.bkfqrSsbmdm = getItem("deptId")[0].deptCode;;
  }
  title.value = type == 'add' ? '新增' : type == 'detail' ? '详情' : '编辑';
  disabled.value = type == 'detail' ? true : false;
  dialogForm.value = true;
  if (row) tableDate.tableConfiger.haveControls = false;
  Zd({D_GS_BK_DJ:props.dic.D_GS_BK_DJ,BD_BK_CLYJBQ:props.dic.BD_BK_CLYJBQ})

  get_bkqy_list(row)
};

// 获取布控区域
const get_bkqy_list = (row) => {
  qcckGet({}, '/mosty-gsxt/tbGsxtBkQy/selectList').then(res => {
    let arr = res || [];
    bkqyArr.value = arr.map(item => {
      return { ...item, label: item.qymc, value: item.id }
    })
    if (row) getDataById(row.id);
  })
}
const dataOrge=ref({})
const approvalEcho = ref()
watch(() => approvalEcho.value, (val) => {
  if (val) {
  approvalEcho.value.getWorkflow(dataOrge.value.gzlid)
  }

},{deep:true})

// 根据id获取详情
const getDataById = (id) => {
  qcckGet({}, '/mosty-gsxt/tbGsxtBk/selectVoById/' + id).then(res => {
    res.bkfj = res.ossList || [];
    res.bkqyList = res.qyList ? res.qyList.map(v => v.id) : [];
    listQuery.value = res || {}
    dataOrge.value=res
    tableDate.tableColumn = tableColumnList[res.bkDx ? res.bkDx : '01']
  })
}
watch(() => approvalEcho.value, (val) => {
  if (val) {
    console.log(approvalEcho.value);
  approvalEcho.value.getWorkflow(dataOrge.value.gzlid)
  }

},{deep:true})


const shangeDx = () => {
  tableDate.tableColumn = tableColumnList[listQuery.value.bkDx]
  listQuery.value.bkDxxx = '';
  listQuery.value.bkdxList = [];
  roleIds.value = [];
  addPerson.value = []
}
// 删除数据
const deleteRow = (row) => {
  roleIds.value = roleIds.value.filter(id => id != row.id);
  addPerson.value = addPerson.value.filter(it => it.id != row.id);
  listQuery.value.bkdxList = listQuery.value.bkdxList.filter(it => it.id != row.id);
}
// 单独新增的数据
const choosedAdd = (item) => {
  let obj = {}
  if (listQuery.value.bkDx !== '02') {
    obj = { id: item.id, fjZp: item.fjZp, ryXm: item.ryXm, ryXb: item.ryXb, rySfzh: item.rySfzh, ryHjd: item.hjdXz, ryXjd: item.xzdXz, rySjhm: item.ryLxdh, qtXnsf: item.qtXnsf, clCjh: item.clCjh, clCph: item.clCph, qtTzms: item.qtTzms, bqList: item.bqList }
  } else {
    obj = {
      clCph: item.hphm, clCjh: item.clCjh, clSyr: item.clSyr, clSyrsfzh: item.clSyrsfzh,
      clYs: item.clYs, gxSsbmmc: item.gxSsbmmc, bqList: item.bqList
    }
  }
  switch (listQuery.value.bkDx) {
    default:
      obj = { ...item }
      break;
  }
  addPerson.value.push(obj);//缓存的数据
  if (!listQuery.value.bkdxList) listQuery.value.bkdxList = [];
  listQuery.value.bkdxList.unshift(obj);
  console.log(listQuery.value.bkdxList);

}

// 选择重点人
const choosed = (val) => {
  tableDate.tableColumn = tableColumnList[listQuery.value.bkDx]
  if (listQuery.value.bkDx == '01') {// 人员
    roleIds.value = val.map(it => it.id);
    let arr = val.map(item => {
      let bqArr = item.bqList || [];
      let bqs = bqArr.map(v => {
        return { bqZl: v.bqZl, bqId: v.bqId, bqLx: v.bqLx, bqLb: v.bqLb, bqMc: v.bqMc, bqDm: v.bqDm }
      })
      return {
        id: item.id, fjZp: item.fjZp, ryXm: item.ryXm, ryXb: item.ryXb,
        rySfzh: item.rySfzh, ryHjd: item.hjdXz, ryXjd: item.xzdXz,
        rySjhm: item.ryLxdh, qtXnsf: item.qtXnsf, clCjh: item.clCjh,
        clCph: item.clCph, qtTzms: item.qtTzms, bqList: bqs,  yjdj: item.zdrYjdj,ssbmdm:item.zrSsbmdm
      }
    })
    listQuery.value.bkdxList = [...addPerson.value, ...arr];
  } else if (listQuery.value.bkDx == '03') {
    roleIds.value = val.map(it => it.id);
    let arr = val.map(item => {

      return {
        clCph: item.hphm, clCjh: item.clCjh, clSyr: item.clSyr, clSyrsfzh: item.clSyrsfzh,
        clYs: item.clYs, gxSsbmmc: item.gxSsbmmc,yjbq: item.yjbq, yjdj: item.yjdj,ssbmdm:item.zrSsbmdm
      }
    })
    listQuery.value.bkdxList = [...addPerson.value, ...arr];

  }
  else {// 群体
    listQuery.value.bkDxxx = (val.map(it => it.id)).join(',');
    let peolist = []
    val.forEach(item => {
      if (item.zdryList) peolist = peolist.concat(item.zdryList)
    })
    let brrPeo = peolist.map(item => {
      let bqArr = item.bqList || [];
      let bqs = bqArr.map(v => {
        return { bqZl: v.bqZl, bqId: v.bqId, bqLx: v.bqLx, bqLb: v.bqLb, bqMc: v.bqMc, bqDm: v.bqDm }
      })
      return {
        id: item.id, fjZp: item.fjZp, ryXm: item.ryXm, ryXb: item.ryXb,
        rySfzh: item.rySfzh, ryHjd: item.hjdXz, ryXjd: item.xzdXz,
        rySjhm: item.ryLxdh, qtXnsf: item.qtXnsf, clCjh: item.clCjh,
        clCph: item.clCph, qtTzms: item.qtTzms, bqList: bqs,
        yjdj: item.zdrYjdj,ssbmdm:item.zrSsbmdm
      }
    })
    listQuery.value.bkdxList = brrPeo;
  }
};

// 选择人员
const handleAddPeo = () => {
  if (!listQuery.value.bkDx) return proxy.$message({ type: "warning", message: '请选择布控对象' });
  switch (listQuery.value.bkDx) {
    case '01':
      chooseVisible_RY.value = true
      break;
    case '04':
    case '05':
    case '06':
    case '07':
    case '08':
    case '09':
    case '10':
      chooseVisible_SFZ.value = true
      break;
    case '03':
      chooseVisible_CL.value = true
      break;
    case '02':
      chooseVisible_QT.value = true
      break;
  }
}


// 提交
const submit = () => {
  elform.value.validate((validate) => {
    if (!validate) return;
    let params = { ...listQuery.value };
    params.bkfj = params.bkfj ? params.bkfj.join(',') : '';
    params.bkdxList = params.bkdxList ? params.bkdxList : [];
    params.bkdxList.forEach(item => { item.fjZp = item.fjZp ? item.fjZp.join(',') : '' })
    loading.value = true;
    let url = title.value == '新增' ? "/mosty-gsxt/tbGsxtBk/save" : "/mosty-gsxt/tbGsxtBk/update";
    qcckPost(params, url).then((res) => {
      proxy.$message({ type: "success", message: "布控成功" });
      emit("change");
      loading.value = false;
      close();
    }).catch(() => {
      loading.value = false;
    });
  });
};

// 关闭
const close = () => {
  listQuery.value = {};
  dialogForm.value = false;
  loading.value = false;
  addPerson.value = [];
  roleIds.value = []
  dataOrge.value={}
};
// 选择身份证
const chooseVisible_SFZ = ref(false)
// 获取布控信息的工作流
const workflow = ref()
const getWorkflow = async (id) => {
  const promes = {
    processId: id
  }
  const proNode = await queryProcessNode(promes)
  const proNodeLog = await queryProcessNodeLog(promes)
  const process = await queryProcess(promes)
  workflow.value = proNode.rows.map(item => {
    const log = proNodeLog.rows.filter(items => item.nodeId == items.nodeId)

    if (item.eventType == '0') {
      return {
        ...item,
        log: {
          userData: item.userData ? JSON.parse(item.userData) : JSON.parse(process.rows[0].processData).orgNameData,
          userName: process.rows[0].userName,
          xtLrsj: process.rows[0].xtLrsj,
          processStatus: process.rows[0].processStatus,
        }
      }
    } else {
      return {
        ...item,
        orgNameData: JSON.parse(log[0].userData),
        log: log
      }
    }

  })

};

defineExpose({ init });
</script>

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

.smallTitle {
  width: 100%;
  font-size: 15px;
  line-height: 50px;
  font-weight: 550;
  color: #606266;
}

.mapSearch {
  left: 10px;
  top: 10px;
  z-index: 100;
}

.dialog {
  ::v-deep .el-form-item--default {
    margin: 0 1% 0 0 !important;
    padding-bottom: 0 !important;
  }
}

::v-deep .avatar-uploader {
  display: flex;
}

::v-deep .el-upload--picture-card i {
  width: 156px;
}

.depBox {
  border: 1px solid #e9e9e9;
  width: 305px;
  padding: 0 0 0 4px;
  border-radius: 4px;

  ::v-deep .el-input__inner {
    border: none;
  }

  ::v-deep .el-cascader .el-input.is-focus .el-input__inner {
    border-color: transparent !important;
  }

  ::v-deep .el-input__inner:focus {
    box-shadow: none;
  }

  ::v-deep .el-input.is-disabled .el-input__inner {
    border-color: transparent !important;
  }

}

/* 使用深度选择器覆盖子组件样式 */
::v-deep .el-step.is-vertical .el-step__title {
  color: #000000 !important;
  border-color: #000000 !important;
}
::v-deep .el-step__description{
  padding: 0 !important;
}
::v-deep .el-step__description.is-wait {

  color: #000000 !important;
  border-color: #000000 !important;
}

.el-step__title.is-wait {
  color: #000000 !important;
  border-color: #000000 !important;
}

::v-deep .el-step__head.is-wait {
  color: #000000 !important;
  border-color: #000000 !important;
}

::v-deep .el-step__line {
  background-color: #000000 !important;
}

.nodeBox {
  width: 80%;
  text-align: center;
  line-height: 30px;
  border-radius: 10px;
  overflow: hidden;
  background-color: aliceblue;

  .nodeorgNameTg {
    background-color: #1abe20;
  }

  .nameTag {
    line-height: 30px;
    padding: 0 10px;
  }

  .nodeorgNameDd {
    background-color: #18a2dd;
  }

  .fontColor {
    color: #1abe20;
  } .fontColorDd {
    color: #18a2dd;
  }
}
</style>
