<template>
  <div class="pblm-detail-wrapper">
    <van-form @submit="onSubmit">
      <card01 v-if="pblm && pblm.length > 0"
              :description="`工程地址：${pblm.location}<br/>问题类型：${listTypeConvert(pblm.listType)}`"
              :title="pblm.name + ''" icon="label"
              style="margin-top: 0;"/>
      <div class="pblm-detail-label">
        <span>违规事项</span>
        <van-button size="mini" type="primary" @click="showTacObjPblmstbPopup()">选择违规事项</van-button>
      </div>
      <van-cell-group inset>
        <van-field v-model="tacObjPblmstb.pblmTypeDesc" autosize label="问题类型" label-align="top"
                   placeholder="问题类型" readonly rows="1" type="textarea"/>
        <van-field v-model="tacObjPblmstb.pblmsDesc" autosize label="违规事项" label-align="top" placeholder="违规事项"
                   readonly rows="2" type="textarea"/>
        <van-field v-model="tacObjPblmstb.relativeLaw" autosize label="法规条款" label-align="top"
                   placeholder="法规条款" readonly rows="2" type="textarea"/>
        <van-field v-model="tacObjPblmstb.lawContent" autosize label="法规内容" label-align="top" placeholder="法规内容"
                   readonly rows="2" type="textarea"/>
        <van-field v-model="pblm.note" autosize label="备注" label-align="top" placeholder="备注" rows="2"
                   type="textarea"/>
      </van-cell-group>
      <div class="pblm-detail-label">问题描述</div>
      <van-cell-group inset>
        <van-field v-model="pblm.pblmNm" autosize label="发现问题" label-align="top" placeholder="发现问题" rows="2"
                   type="textarea"/>
        <van-field v-model="pblm.pblmDesc" autosize label="问题阐述" label-align="top" placeholder="问题阐述" rows="2"
                   type="textarea"/>
        <van-field v-model="pblm.pblmReason" autosize label="主要原因分析" label-align="top" placeholder="主要原因分析"
                   rows="2" type="textarea"/>
        <van-field v-model="pblm.pblmSggtn" autosize label="整改意见及建议" label-align="top"
                   placeholder="整改意见及建议"
                   rows="2" type="textarea"/>
        <van-field v-model="pblm.spclRvwOptn" autosize label="稽察组长复核意见" label-align="top"
                   placeholder="稽察组长复核意见"
                   rows="2" type="textarea"/>
        <GwSelect02 v-model:value="pblm.pblmPasi" :columns="cateObjList" label="问题严重性"></GwSelect02>
        <van-field label="是否典型问题" name="radio">
          <template #input>
            <van-radio-group v-model="pblm.ifCasePblm" direction="horizontal">
              <van-radio name="1">是</van-radio>
              <van-radio name="0">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field label="排序序号" name="stepper">
          <template #input>
            <van-stepper v-model="pblm.sn"/>
          </template>
        </van-field>
        <van-field label="文件上传" label-align="top" name="uploader">
          <template #input>
            <van-uploader v-model="gwComFileList"/>
          </template>
        </van-field>
      </van-cell-group>
      <div class="pblm-detail-label">责任主体</div>
      <van-cell-group inset>
        <div v-for="(item, index) in subjectList" :key="item.id" class="pblmSubjectList">

          <van-row style="border-bottom: 1px dashed #CDD0D6;">
            <van-col span="20">
              <GwSelect02 v-model:value="item.subId" :columns="objSubjectTypeColumns" label="单位性质"></GwSelect02>
              <GwSelect02 v-model:value="item.unitNm" :columns="getObjSubjectColumns(index)"
                          label="单位名称">
              </GwSelect02>
            </van-col>
            <van-col span="4" style="display: flex;justify-content: center;align-items: center;"
                     @click="removePblmSubject(index)">
              <van-icon color="#000" name="delete-o" size="1rem"/>
            </van-col>
          </van-row>
        </div>
        <van-button block hairline plain round @click="addPblmSubject">
          <van-icon color="#000" name="plus" size="1rem" style="margin-right: 5px;"/>
          添加单位
        </van-button>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button block native-type="submit" round type="primary">
          提交
        </van-button>
      </div>
    </van-form>

    <van-popup v-model:show="tacObjPblmstbShow" :style="{ width: '80%', height: '100%' }" position="left">
      <tacObjPblmstbList :listType="pblm.listType" style="z-index:3000;"
                         @change="changeTacObjPblmstb"></tacObjPblmstbList>
    </van-popup>
  </div>
</template>
<script setup>
import {computed, onMounted, ref, watch} from "vue";
import {useRoute} from "vue-router";
import {showNotify} from 'vant';
import card01 from '@/components/card01.vue';
import GwSelect02 from '@/components/GwSelect02.vue';
import tacObjPblmstbList from './TacObjPblmstbList.vue';
import {listTypeConvert} from "@/utils/convert";
import {getTacQuestionById} from "@/api/inspect";
import {addTacQuestion, getIllegalActById, getTacUnitList} from "@/api/questions";
import {copyObj} from "@/utils/ruoyi";
import {useUserStore} from "@/stores/user";

const route = useRoute();
const userStore = useUserStore();
const listType = ref(route.query.inspectType || '1');
const pblm = ref({});
const tacObjPblmstb = computed(() => pblm.value.tacObjPblmstb || {});
const cateObjList = ref([]);
const objSubjectList = ref([]);
// const objSubjectTypeColumns = computed(() => objSubjectList.value?.map(i => {
//   return {text: i.subName, value: i.id}
// }) || []);
const objSubjectTypeColumns = computed(function() {
  let list = objSubjectList.value ? objSubjectList.value : [];
  let mappedList = list.map(function(i) {
    return {
      text: i.subName,
      value: i.id
    };
  });
  return mappedList || [];
});
const objSubjects = ref({});
// const gwComFileList = computed(() => pblm.value.gwComFileList?.map(i => {
//   return {url: process.env.VUE_APP_BASE_HOST + process.env.VUE_APP_BASE_API + i.filePath}
// }) || []);
const gwComFileList = computed(function() {
  const fileList = pblm.value && pblm.value.gwComFileList ? pblm.value.gwComFileList : [];
  const mappedList = fileList.map(function(item) {
    return {
      url: process.env.VUE_APP_BASE_HOST + process.env.VUE_APP_BASE_API + item.filePath
    };
  });
  return mappedList || [];
});
/**
 * 责任主体
 */
const subjectList = ref([]);
const tacObjPblmstbShow = ref(false);

function getQuestionData() {
  getTacQuestionById(route.params.id).then(res => {
    if (res.data && Object.keys(res.data).length > 0) {
      pblm.value = res.data
      listType.value = res.data.listType
      subjectList.value = res.data.pblmSubjectList;
      cateObjList.value = res.data.tacObjPblmstb.cateObjList.map(i => {
        return {text: i.desc, value: i.cate}
      }) || []
      objSubjectList.value = pblm.value.tacObjPblmstb.objSubjectList
    }
  })
}

/**
 * 选择违规事项
 */
function showTacObjPblmstbPopup() {
  tacObjPblmstbShow.value = true;
}

function changeTacObjPblmstb(data) {
  if (!data || !data.id) {
    return
  }
  getIllegalActById(data.id).then(res => {
    tacObjPblmstbShow.value = false;
    pblm.value.tacObjPblmstb = res.data;
    pblm.value.pblmstdId = res.data.id;
    cateObjList.value = res.data.cateObjList.map(i => {
      return {text: i.desc, value: i.cate}
    }) || []
    objSubjectList.value = res.data.objSubjectList
  })
}

// eslint-disable-next-line no-unused-vars
function uniArr(tempArr) {
  var newTempArr = [];
  if (tempArr && tempArr.length > 0) {
    tempArr.forEach((item) => {
      if (item.unitNm || item.subId) {
        newTempArr.push(item);
      }
    })
    for (let i = 0; i < newTempArr.length; i++) {
      for (let j = i + 1; j < newTempArr.length; j++) {
        if ((newTempArr[i].unitNm == newTempArr[j].unitNm) && (newTempArr[i].subId == newTempArr[j].subId)) {
          newTempArr.splice(j, 1);
          j--;
        }

      }

    }

    return newTempArr;
  } else {
    return [];
  }
}

/**
 * 保存问题
 */
function onSubmit() {
  const data = copyObj(pblm.value)
  if (!data.pblmstdId) {
    showNotify({type: 'warning', message: '请选择问题'});
    return
  }
  if (!data.sn) {
    data.sn = 0
  }
  if (data.pblmReason && data.pblmReason.length >= 500) {
    showNotify({type: 'warning', message: '主要原因分析需字数小于500字！'});
    return;
  }
  if (data.pblmSggtn && data.pblmSggtn.length >= 1000) {
    showNotify({type: 'warning', message: '整改意见及建议字数需小于1000字！'});
    return;
  }
  if (data.spclRvwOptn && data.spclRvwOptn.length >= 500) {
    showNotify({type: 'warning', message: '稽察组长意见字数需小于500字！'});
    return;
  }
  if (data.pblmRevision && data.pblmRevision.length >= 500) {
    showNotify({type: 'warning', message: '问题修改理由字数需小于500字！'});
    return;
  }
  data.relativeLaw = data.tacObjPblmstb.relativeLaw
  data.lawContent = data.tacObjPblmstb.lawContent
  data.pblmSubjectList = subjectList.value
  if (!data.id) {
    // data.stepId  = stepId
    data.objId = route.query.objId;
    data.rgstrId = route.query.rgstrId;
    data.listType = listType.value;
    data.persId = userStore.userId;
  }

  let unitNames = []
  let subIds = []
  const unitArray = uniArr(subjectList.value);
  unitArray.forEach((ele) => {
    unitNames.push(ele.unitNm)
    subIds.push(ele.subId)
  })
  unitNames = unitNames.filter(function (s) {
    return s && s.trim();
  });
  subIds = subIds.filter(function (s) {
    return s && s.trim();
  });
  if ((unitNames.length != subIds.length) && unitNames.length != 0 && subIds.length != 0) {
    showNotify({type: 'warning', message: '对应的单位性质或单位名称其中一个不能为空'});
    return false;
  }
  data.subjectNames = unitNames.join(',')
  data.subjectIds = subIds.join(',')


  addTacQuestion(data).then(res => {
    pblm.value.id = res.data.id
    showNotify({type: 'success', message: '保存成功'});
  })
}

async function getObjSubjects(rgstrId, subId) {
  if (rgstrId && subId) {
    return await getTacUnitList(rgstrId, subId).then(res => res.data) || []
  } else {
    return []
  }
}

function getObjSubjectColumns(index) {
  return (objSubjects.value[index] || []).map(i => {
    return {text: i.sysNm, value: i.sysNm}
  })
}

/**
 * 添加责任主体
 */
function addPblmSubject() {
  subjectList.value.push({});
}

function removePblmSubject(index) {
  subjectList.value.splice(index, 1);
}

onMounted(() => {
  getQuestionData();
})

watch(() => subjectList, (list) => {
  if (list.value && list.value.length > 0) {
    list.value.forEach((item, index) => {
      if (item.subId) {
        getObjSubjects(pblm.value.rgstrId, item.subId).then(res => {
          objSubjects.value[index] = res;
        })
      }
    })
  }
}, {deep: true, immediate: true})
</script>
<style lang="scss" scoped>
.pblm-detail-wrapper {
  height: 100%;
  padding: 10px 0;
  overflow: auto;

  .pblm-detail-label {
    padding: 10px 16px;
    color: #606266;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

}
</style>
<style lang="scss">
.van-cell-group--inset {
  margin: 0 10px;
}
</style>
