﻿<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : isDetail ? '详情' : '编辑'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    class="NCC-dialog NCC-dialog_center"
    lock-scroll
    width="60%"
    v-loading="loading"
  >
    <el-row :gutter="15" class="NCC-dialog-content">
      <el-form
        ref="elForm"
        :model="dataForm"
        size="small"
        label-width="100px"
        label-position="right"
        :disabled="!!isDetail"
        :rules="rules"
      >
        <el-col :span="23" v-if="false">
          <el-form-item label="主键" prop="id">
            <el-input
              v-model="dataForm.id"
              placeholder="请输入"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="23" v-if="ncc.hasFormP('title')">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="dataForm.title"
              placeholder="请输入"
              clearable
              required
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="23" v-if="ncc.hasFormP('content')">
          <el-form-item label="内容" prop="content">
            <NCC-Quill v-model="dataForm.content" placeholder="请输入内容...">
            </NCC-Quill>
          </el-form-item>
        </el-col>
        <el-col :span="23" v-if="ncc.hasFormP('annex')">
          <el-form-item label="附件" prop="annex">
            <NCC-UploadFz
              v-model="dataForm.annex"
              :fileSize="5"
              sizeUnit="MB"
              :limit="9"
              buttonText="点击上传"
            >
            </NCC-UploadFz>
          </el-form-item>
        </el-col>
        <el-col :span="23" v-if="ncc.hasFormP('communicationArea')">
          <el-form-item label="传达区域" prop="communicationArea">
            <el-checkbox-group v-model="dataForm.communicationArea" :style="{}">
              <el-checkbox
                v-for="(item, index) in areaOptions"
                :key="index"
                :label="item.id"
                :disabled="editType == '已发布并部署' || editType == '已发布'"
                >{{ item.fullName }}</el-checkbox
              >
            </el-checkbox-group>
            <div style="margin-top: 10px" v-if="!editType || editType == '已存档'">
              <el-button size="mini" @click="selectAreaAll('area')">全选</el-button>
              <el-button size="mini" @click="closeAreaAll('area')">反选</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="23" v-if="ncc.hasFormP('communicationOut')">
          <el-form-item label="传达外协" prop="communicationOut">
            <el-checkbox-group v-model="dataForm.communicationOut" :style="{}">
              <el-checkbox
                v-for="(item, index) in communicationOutOptions"
                :key="index"
                :label="item.id"
                :disabled="editType == '已发布并部署' || editType == '已发布'"
                >{{ item.fullName }}</el-checkbox
              >
            </el-checkbox-group>
            <div style="margin-top: 10px" v-if="!editType || editType == '已存档'">
              <el-button size="mini" @click="selectAreaAll">全选</el-button>
              <el-button size="mini" @click="closeAreaAll">反选</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="23" v-if="ncc.hasFormP('relationId')">
          <el-form-item label="填报表单" prop="relationId">
            <el-select v-model="dataForm.relationId" placeholder="请选择专项行动填报表单" style="margin-right: 10px;width: 300px;" :disabled="editType == '已发布并部署'">
              <el-option v-for="item in BaseList" :key="item.id" :label="item.fullName" :value="item.id">
              </el-option>
            </el-select>
            <div v-if="dataForm.relationId"  style="display: inline-block; margin-right: 14px;">
              <FormDialog :row="{formId: dataForm.relationId}" :isDetail="true">预览表单</FormDialog>
            </div>
            <el-button size="mini" type="text" @click="dialogVisible = true">没有找到表单？点击设计表单</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="23" v-if="ncc.hasFormP('deadline')">
          <el-form-item label="截止时间" prop="deadline">
            <el-date-picker
              v-model="dataForm.deadline"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              :disabled="editType == '已发布并部署'"
              placeholder="选择截止时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit(0)" v-if="!isDetail" :loading="btnLoading">保 存</el-button>
      <el-button type="primary" @click="dataFormSubmit(1)" v-if="!isDetail" :loading="btnLoading">发 布</el-button>
      <el-button type="primary" @click="dataFormSubmit(2)" v-if="!isDetail" :loading="btnLoading">发布并反馈</el-button>
    </span>
    <el-dialog class="zxDialog" title="专项行动表单设计" :visible.sync="dialogVisible" fullscreen @close="handleClose" :modal="false">
      <iframe 
        :src="nestedPageUrl" 
        width="100%" 
        :height="viewportHeight - 58 + 'px'" 
        frameborder="0" 
        allowfullscreen>
      </iframe>
    </el-dialog>
  </el-dialog>
</template>
<script>
import request from "@/utils/request";
import ncc from "@/utils/ncc.js"
import { getDictionaryDataSelector } from "@/api/systemData/dictionary";
import { previewDataInterface } from "@/api/systemData/dataInterface";
export default {
  components: {},
  props: [],
  data() {
    var validatecommunicationArea = (rule, value, callback) => {
        if (!this.dataForm.communicationOut.length && !value.length) {
          callback(new Error('传输区域和传输外协不能同时为空！'));
        } else {
          callback();
        }
      };
    var validatecommunicationOut = (rule, value, callback) => {
      if (!this.dataForm.communicationArea.length && !value.length) {
        callback(new Error('传输区域和传输外协不能同时为空！'));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      visible: false,
      isDetail: false,
      editType: '', // 修改类型
      dataForm: {
        id: "",
        id: undefined,
        title: undefined,
        content: undefined,
        releaseTime: undefined,
        annex: [],
        communicationArea: [],
        communicationOut: [],
        state: undefined,
        creatorUserId: undefined,
        creatorTime: undefined,
        lastModifyUserId: undefined,
        lastModifyTime: undefined,
        deadline: undefined,
        relationId: undefined,
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
        communicationArea: [{validator: validatecommunicationArea, trigger: 'blur'}],
        communicationOut: [{validator: validatecommunicationOut, trigger: 'blur'}],
        relationId: [{ required: true, message: "请选择专项行动填报表单", trigger: "blur"}],
        deadline: [{ required: true, message: "请选择截止日期", trigger: "blur" }],
      },
      areaOptions: [],
      communicationOutOptions: [],
      BaseList:[],
      viewportHeight: 0,
      // nestedPageUrl:"http://8.130.38.56:8043/old/#/onlineDev/webDesign/indexNew",
      nestedPageUrl:"http://118.122.147.194:5000/old/#/onlineDev/webDesign/indexNew",
      dialogVisible: false,
      btnLoading: false
    };
  },
  computed: {},
  watch: {},
  created() {
    this.initAreaTypeList();
    this.initCommunicationOutOptions();
    this.updateViewportHeight();
    this.getDataForm();
      // 监听窗口大小变化事件
      window.addEventListener('resize', this.updateViewportHeight);
  },
  mounted() {},
  beforeDestroy() {
    // 移除窗口大小变化事件监听器
    window.removeEventListener('resize', this.updateViewportHeight);
  },
  methods: {
    updateViewportHeight() {
      // 获取页面显示高度
      this.viewportHeight = window.innerHeight || document.documentElement.clientHeight;
    },
    handleClose() {
      // 这里是对话框关闭后需要执行的代码
      this.getDataForm();
      // 例如，你可以在这里添加任何其他的逻辑
    },
     //查询表单
     getDataForm() {
      request({
        url: "/visualdev/Base?type=1",
        method: "get",
      }).then((res) => {
        this.BaseList = res.data.list[0].children;
      });
    },
    async initAreaTypeList() {
      let list = this.$store.state.meta.area;
      !list && (list = await this.$store.dispatch("getTypeListByCode", "area"));
      this.areaOptions = list;
    },
    async initCommunicationOutOptions() {
      let list = this.$store.state.meta.externalAssistanceList;
      !list && (list = await this.$store.dispatch("getTypeListByCode", "externalAssistance"));
      this.communicationOutOptions = list;
    },
    // 全选
    selectAreaAll(type) {
      if(type == 'area') {
        this.dataForm.communicationArea = this.areaOptions.map(
          (option) => option.id
        );
      } else {
        this.dataForm.communicationOut = this.communicationOutOptions.map(
          (option) => option.id
        );
      }
    },
    // 反选
    closeAreaAll(type) {
      if(type == 'area') {
        this.dataForm.communicationArea = this.areaOptions.filter((option) => !this.dataForm.communicationArea.includes(option.id)).map((option) => option.id);
      } else {
        this.dataForm.communicationOut = this.communicationOutOptions
          .filter(
            (option) => !this.dataForm.communicationOut.includes(option.id)
          )
          .map((option) => option.id);
      }
    },
   
    goBack() {
      this.$emit("refresh");
    },
    init(row, isDetail) {
      this.dataForm.id = row ? row.id : '';
      this.visible = true;
      this.isDetail = isDetail || false;
      this.editType = row ? row.state : '';
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if(this.dataForm.id) {
          request({
            url: `/Extend/BaseSpecialAction/${this.dataForm.id} `,
            method: "GET",
          }).then((res) => {
            this.dataForm = res.data;
            this.dataForm.deadline = new Date(ncc.dateFormat(res.data.deadline, 'YYYY-MM-DD HH:mm:ss'));
            this.dataForm.annex = res.data.annex == null ? [] : res.data.annex;
          })
        }
      });
    },
    dataFormSubmit(type) {
      this.validateForm(type, () => {
        let obj = {
          ...this.dataForm,
          state: type
        }
        let url = !this.dataForm.id ? '/Extend/BaseSpecialAction/Release' : '/Extend/BaseSpecialAction/Update';
        let method = !this.dataForm.id ? 'PUT' : 'POST';
        this.toPostForm(url, method, obj);
      });
    },
    validateForm(type, callback) {
      let list = ['title', 'content'];
      switch (type) {
        case 0:
        list = ['title', 'content'];
          break;
        case 1:
        list = ['title', 'content', 'communicationArea', 'communicationOut'];
          break;
        case 2:
        list = ['title', 'content', 'communicationArea', 'communicationOut', 'relationId', 'deadline'];
          break;
      
        default:
          break;
      }
      let Promises =  list.map(v => new Promise((resolve, reject) => this.$refs["elForm"].validateField(v, err => resolve(err))));
      Promise.all(Promises).then(values => {
        if(values.filter(item =>item).length) {
          return
        } else {
          callback && callback(values);
        }
      });
    },
    toPostForm(url, method, obj, callback) {
      this.btnLoading = true;
      request({
        url,
        method,
        data: obj,
      }).then((res) => {
        this.$message({
          message: res.msg,
          type: "success",
          duration: 1000,
          onClose: () => {
            callback && callback();
            this.btnLoading = false;
            (this.visible = false), this.$emit("refresh", true);
          },
        });
      }).catch(() => this.btnLoading = false);
    }
  },
};

</script>
<style lang="scss" scoped>
.zxDialog {
  :deep(.el-dialog__body) {
    max-height: 90vh !important;
  }
}
</style>
