<template>
  <div>
    <div
      class="dialog-h-content scroll-h"
      :class="{ 'visiual-form': source === 'visiual' }"
    >
      <el-form
        ref="ref_gxxq_form"
        :inline="true"
        :model="formData"
        :rules="dataRule"
        class="div_form"
      >
        <!-- 需求类别 -->
          
        <el-form-item label="需求类型" prop="categoryCode" label-width="150px">
          <el-cascader
            v-model="formData.categoryCode"
            :options="demandOptions"
            :props="{label: 'categoryName',value: 'categoryCode',children: 'childCateList'}"
            clearable
            size="small"
            ref="categoryCode"
            class="u-item-width-normal"
            @change="handelChangeCategoryCode"
          ></el-cascader>
          </el-form-item>
        <el-form-item
          label="需求标题"
          prop="title"
          label-width="150px"
          :class="{ 'form-item': source === 'visiual' }"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            placeholder="请输入需求标题"
            v-model="formData.title"
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="详细说明"
          prop="content"
          label-width="150px"
          :class="{ 'form-item': source === 'visiual' }"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            type="textarea"
            maxlength="1000"
            show-word-limit
            :rows="3"
            placeholder="请输入备注，不超过1000字"
            v-model="formData.content"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="查找有该需求人员"
          prop="resiSearchTagId"
          :class="{ 'form-item': source === 'visiual' }"
          label-width="150px"
          style="display: block"
        >
          <template v-if="formData.resiSearchTagName">
            <el-tag @close="handleCloseTag" closable style="margin-right: 10px">
              {{ formData.resiSearchTagName }}
            </el-tag>
          </template>
          <el-button type="primary" @click="handleClickLabel" size="mini">
            <span> <i class="el-icon-plus"></i> 按标签查找 </span>
          </el-button>
        </el-form-item>
        <el-form-item label="指派服务" label-width="150px">
          <el-switch
            v-model="formData.assignFlag"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
      </el-form>
        
      <el-form :model="newFormData" :rules="newDataRule" ref="ref_gxxq_form1" class="div_form">
        <el-form-item
          v-if="formData.assignFlag"
          label="服务方"
          label-width="150px"
          style="display: block"
          prop="serverOrgId"
        >
          <el-select
            v-model="newFormData.serverOrgType"
            class="input-width-small"
            placeholder="请选择"
            clearable
            @change="handleServiceChange('add', $event)"
          >
            <el-option
              v-for="item in serviceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          -
          <el-select
            v-model="newFormData.serverOrgId"
            class="input-width-middle"
            filterable
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in serviceOptiondList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.assignFlag"
          prop="noticeApproches"
          label="自动通知服务方"
          label-width="150px"
          style="display: block"
        >
          <el-checkbox-group v-model="newFormData.noticeApproches">
            <el-checkbox label="1" value="1">短信通知</el-checkbox>
            <el-checkbox label="2" value="2">微信公众号消息通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item
          v-if="formData.assignFlag"
          label="服务范围"
          label-width="150px"
          style="display: block"
          prop="serviceScopeList"
        >
          <el-cascader
            class="item_width_1"
            ref="myCascader"
            v-model="newFormData.serviceScopeList"
            :key="iscascaderShow"
            :options="casOptions"
            :props="optionProps"
            collapse-tags
            :show-all-levels="false"
          ></el-cascader>
        </el-form-item>

        <el-form-item
          v-if="formData.assignFlag"
          label="服务时间"
          label-width="150px"
          prop="serviceTimeEnd"
        >
          <el-date-picker
            v-model="newFormData.serviceTimeStart"
            :picker-options="startPickerOptions"
            class="item_width_2"
            style="width: 220px"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            value="yyyy-MM-dd"
            placeholder="开始时间"
          >
          </el-date-picker>
          <span class="u-data-tag">至</span>
          <el-date-picker
            v-model="newFormData.serviceTimeEnd"
            :picker-options="endPickerOptions"
            class="item_width_2 u-data-tag"
            style="width: 220px"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            value="yyyy-MM-dd"
            placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </div>

    <div class="div_btn">
      <el-button size="small" @click="handleCancle">取 消</el-button>
      <el-button
        size="small"
        type="primary"
        :disabled="btnDisable"
        @click="handleComfirm"
        >确 定</el-button
      >
    </div>

    <el-dialog
      v-if="showLabelForm"
      :visible.sync="showLabelForm"
      :append-to-body="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="'标签配置'"
      width="954px"
      top="5vh"
      class="dialog-h"
      @closed="showLabelForm = false"
    >
      <label-form
        ref="ref_label_form"
        @dialogCancle="addFormCancle"
        @dialogOk="addFormOk"
      >
      </label-form>
    </el-dialog>
  </div>
</template>
  
    <script>
import { mapGetters } from "vuex";
import { Loading } from "element-ui"; // 引入Loading服务
import { requestPost, requestGet } from "@/js/dai/request";
// import personList from "../policy/oldPersonList.vue";
import nextTick from "dai-js/tools/nextTick";
import labelForm from "../labelConfig/addForm.vue";

let loading; // 加载动画
let map;

export default {
  props: {
    defaultData: {
      type: Object,
      default: null,
    },
    serviceRecordId: {
      type: String,
      required: "",
    },
    serviceProjectName: {
      //服务项目名称
      type: String,
      required: false,
      default: "",
    },
    categrayArray: {
      type: Array,
      default() {
        return [];
      },
    },
    source: {
      //展示来源：manage  管理平台    visiual  可视化平台
      type: String,
      default: "manage",
    },
  },

  data() {
    let endDisabledDate = (time) => {
      //这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now();
      if (this.newFormData.serviceTimeStart) {
        let serviceTimeStart = new Date(this.newFormData.serviceTimeStart);
        return (
          time.getTime() < serviceTimeStart - 24 * 60 * 60 * 1000 ||
          time.getTime() === serviceTimeStart - 24 * 60 * 60 * 1000
        );
      } else {
        return time.getTime() > nowData || time.getTime() === nowData;
      }
    };

    let startDisabledDate = (time) => {
      //这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now() - 24 * 60 * 60 * 1000;
      return time.getTime() < nowData || time.getTime() === nowData;
    };

    return {
      // 公共服务分类
      formType: "",
      btnDisable: false,
      casOptions: [],
      scopeIdArray: [],
      iscascaderShow: 0,

      demandOptions:[],

      optionProps: {
        multiple: true,
        value: "objectId",
        label: "objectName",
        children: "children",
        checkStrictly: true,
        emitPath: false,
      },
      newArr: [],
      formData: {
        categoryCode:[],
        parentCategoryCode:'',
        assignFlag: 0,
        resiSearchTagId: "", //查找享受服务人员
        resiSearchTagName: "", //享受服务人员名称
        title: "", //服务名称
        assignInfo: {},
        content: "", //
      },
      endPickerOptions: {
        disabledDate: endDisabledDate,
      },
      startPickerOptions: {
        disabledDate: startDisabledDate,
      },
      newFormData: {
        noticeApproches: [], //服务范围
        serviceScopeList: [], //通知服务方
        serviceTimeStart: "", //服务起始时间yyyy-MM-dd
        serviceTimeEnd: "", //服务截止时间yyyy-MM-dd
        serverOrgType: "", //服务组织类型 社区自组织：community_org， 志愿者：ic_user_volunteer， 联建单位：party_unit
        serverOrgId: "", //服务组织Id
      },
      dataRule: {
        commonServiceTypeId: [
          { required: true, message: "需求类别不能为空", trigger: "bulr" },
        ],
        title: [
          { required: true, message: "需求标题不能为空", trigger: "bulr" },
        ],

        content: [
          { required: true, message: "详细说明不能为空", trigger: "bulr" },
          { max: 1000, message: "不能超出1000个字符", trigger: "blur" },
        ],
        resiSearchTagId: [
          { required: false, message: "指派人员不能为空", trigger: "bulr" },
        ],
        categoryCode: [
          { required: true, message: "需求分类不能为空", trigger: "bulr" },
        ],
      },
      newDataRule: {
        serverOrgId: [
          { required: true, message: "服务方不能为空", trigger: "bulr" },
        ],
        serviceScopeList: [
          { required: true, message: "服务范围不能为空", trigger: "bulr" },
        ],
        serviceTimeEnd: [
          { required: true, message: "服务时间不能为空", trigger: "bulr" },
        ],
      },
      sarr: [],
      scopeId: "",
      serviceOptions: [],
      originalServiceOptions:[],
      serviceOptiondList: [],
      policyList: [],

      showLabelForm: false,
    };
  },

  watch: {
    "newFormData.serviceTimeEnd": function (val) {
      if (val && val != "") {
        let arrayTemp = val.split(" ");
        this.formData.serviceTimeEnd = arrayTemp[0] + " 23:59:59";
      }
    },
    "formData.assignFlag"(newValue) {
      if (newValue === 1) {
        this.dataRule.resiSearchTagId[0].required = true;
      } else {
        this.dataRule.resiSearchTagId[0].required = false;
      }
    },
  },
  components: { labelForm },
  created() {},
  async mounted() {
    this.startLoading();
    // this.getCategrayList();
    await this.getPolicyList();
    await this.loadScopeTree();
    await this.getDictOptions();
    await this.getDemandOptions()
    this.endLoading();
    // 服务分类下拉（其实是获取的共性服务分类）
  },

  methods: {
    async initForm(type, row) {
      this.formType = type;
      this.scopeId = row.id;
      await this.getDetail(row.id);
    },
    async getDetail(id) {
      const url = `/governance/commonDemand/detail/${id}`;
      const { data, code, msg } = await requestGet(url);

      if (code === 0) {
        this.formData.serviceTypeLevel1Id = data.servicePid;
        this.formData.commonServiceTypeId = data.commonServiceTypeId;
        this.formData.title = data.title;
        this.formData.content = data.content;
        this.formData.assignFlag = data.assignFlag;
        this.formData.resiSearchTagId = data.resiSearchTagId;
        if (data.categoryCode) {
          this.formData.categoryCode = [data.parentCategoryCode, data.categoryCode];
        } else {
          this.formData.categoryCode = [data.parentCategoryCode];
        }
        if (data.assignInfo) {
          this.newFormData.serviceTimeStart = data.assignInfo.serviceTimeStart;
          this.newFormData.serviceTimeEnd = data.assignInfo.serviceTimeEnd;
          this.newFormData.serverOrgType = data.assignInfo.serverOrgType;
          this.newFormData.serverOrgId = data.assignInfo.serverOrgId;
          this.newFormData.noticeApproches = data.assignInfo.noticeApproches;

          for (let i in data.assignInfo.serviceScopeList) {
            this.newFormData.serviceScopeList.push(
              data.assignInfo.serviceScopeList[i].objectId
            );
          }
          await this.getServiceuserList(data.assignInfo.serverOrgType);
        }
        await // this.formData = { ...data };

        await this.getTagName();
      } else {
        this.$message.error(msg);
      }
    },
    async getTagName() {
      const url = "/governance/resiSearchTag/listResiSearchTags";
      let params = {
        pageSize: 99,
      };
      let { data, msg, code } = await requestPost(url, params);
      if (code == 0) {
        let showAddProduct = data.list.filter((item) => {
          return [this.formData.resiSearchTagId].includes(item.tagId);
        });
        if (this.formData.resiSearchTagId) {
          this.formData.resiSearchTagName = showAddProduct[0].tagName;
        } else {
          this.formData.resiSearchTagName = "";
        }
      } else {
        this.$message.error(msg);
      }
    },
    // 服务类型下拉框选中事件
  
    // 如果服务方有选择第一个的话让它更新
    handleChangeServiceTypeLevel2() {
      if (this.newFormData.serverOrgType) {
        this.getServiceuserList(this.newFormData.serverOrgType);
      } else {
        return;
      }
    },
    handleClickLabel() {
      this.showLabelForm = true;
      this.$nextTick(() => {
        this.$refs["ref_label_form"].initForm("info");
      });
    },
    addFormOk(val) {
      this.showLabelForm = false;
      this.formData.resiSearchTagId = val.tagId;
      this.formData.resiSearchTagName = val.tagName;
    },
    addFormCancle() {
      this.showLabelForm = false;
    },
    handleCloseTag() {
      this.formData.resiSearchTagId = "";
      this.formData.resiSearchTagName = "";
    },
    handelChangeCategoryCode() {
          this.serviceOptions = [...this.originalServiceOptions];
          const parentMappings = {
            '公益事业类': ['party_unit', 'community_org'],
            '技能培训类': ['party_unit', 'publicWelfare', 'community_org'],
            '教育讲座类': ['party_unit', 'community_org'],
            '社会治理类': ['party_unit', 'community_org'],
            '公共服务类': ['party_unit', 'community_org', 'publicWelfare'],
            '岗位提供类': ['party_unit', 'community_org'],
          };
          const checkedParent = this.$refs['categoryCode'].getCheckedNodes()[0].parent.label;
          if (parentMappings[checkedParent] && Array.isArray(parentMappings[checkedParent])) {
            this.serviceOptions = this.serviceOptions.filter(item => parentMappings[checkedParent].includes(item.value));
          } else {
            this.serviceOptions = this.originalServiceOptions
          }
    },
    async iniDefaultData() {
      const { defaultData } = this;
      console.log("iniDefaultData3", defaultData);
      if (defaultData) {
        const { serviceOrgType, serviceOrgId, scopeIdArray } = defaultData;
        if (serviceOrgType) {
          this.formData.assignInfo.serviceOrgType = serviceOrgType;
          await this.getServiceuserList(serviceOrgType, "add_demand");
        }
        if (serviceOrgId) {
          this.formData.assignInfo.serviceOrgId = serviceOrgId;
        }
        if (scopeIdArray) {
          this.scopeIdArray = scopeIdArray;
          await nextTick();
        }
      }
    },

    async getPolicyList() {
      const url = "/governance/policy/policyList";

      let params = {};

      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        this.policyList = data;
      } else {
        this.$message.error(msg);
      }
    },
    async getDictOptions() {
      this.$http
        .post("/sys/dict/data/dictlist", {
          dictType: "user_demand_service_type",
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.serviceOptions = res.data;
            this.originalServiceOptions = [...this.serviceOptions];
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },
    async getDemandOptions() {
      this.$http
        .post("/actual/base/serviceitem/listAllCategory")
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.demandOptions = this.getFlagData(
              this.getTreeData(res.data),
              "usableFlag"
            );
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },
    getFlagData(data, flag) {
      if (!Array.isArray(data)) return [];
      let arr1 = data.filter((item) => item[flag]);
      let arr2 = arr1.map((item) => {
        if (item.childCateList)
          return { ...item, childCateList: this.getFlagData(item.childCateList, flag) };
        else return item;
      });
      // console.log('arrr-oppp', arr2)
      return arr2;
    },
    getTreeData(data) {
      if (!Array.isArray(data)) return [];
      let arr = data.map((item) => {
        let _item = {};
        if (item.childCateList) {
          if (item.childCateList.length === 0)
            _item = { ...item, childCateList: undefined };
          else _item = { ...item, childCateList: this.getTreeData(item.childCateList) };
        } else {
          _item = { ...item };
        }
        return _item;
      });
      return arr;
    },
    async handleServiceChange(type, val) {
      this.newFormData.serverOrgId = ''
      await this.getServiceuserList(val);
    },

    async getServiceuserList(serverOrgType) {
      if (this.formData.categoryCode.length === 0) return;
      const url = "/actual/base/serviceitem/listServerOrgNewTask";
      let params = {
        serverOrgCategoryCode: this.formData.categoryCode[1],
        serverParentOrgCategoryCode:this.formData.categoryCode[0],
        serverOrgType: serverOrgType,
      };
      let { data, code, msg } = await requestPost(url, params);
      if (code == 0) {
        this.serviceOptiondList = data;
      } else if (code >= 8000) {
        this.$message.error(msg);
      }
    },

    // 获取服务范围树
    async loadScopeTree() {
      const url = "/gov/org/icServiceProject/service/serviceScopeTree";
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {};
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        ++this.iscascaderShow;
        this.casOptions = [];
        this.scopeIdArray = [];
        await this.handleData(data.children);
        this.casOptions.push(data);
      } else {
        this.$message.error(rspMsg);
      }
    },
   
    //子级为空数组的赋值为null解决有空白页的问题
    handleData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children != null) {
          if (data[i].children.length == 0) {
            data[i].children = null;
          } else if (data[i].children != null) {
            this.handleData(data[i].children);
          }
        }
      }
      return data;
    },
    async handleComfirm() {
      this.handleAdd();
    },
    getLastItem(list, vals, key) {
      let LIST = list || [];
      for (let item of LIST) {
        // console.log(item[key]);
        for (let i of vals) {
          if (item[key] === i) {
            this.sarr.push(item);
          } else if (item["objectType"] == "district") {
            this.getLastItem(item.children, vals, key);
          } else {
            this.getLastItem(item.children, vals, key);
          }
        }
      }
    },
    async handleAdd() {
      this.btnDisable = true;
      setTimeout(() => {
        this.btnDisable = false;
      }, 10000);
      nextTick(1000);

      const form = new Promise((resolve, reject) => {
        this.$refs["ref_gxxq_form"].validate((valid) => {
          if (valid) resolve();
        });
      });

      const form1 = new Promise((resolve, reject) => {
        this.$refs["ref_gxxq_form1"].validate((valid) => {
          if (valid) resolve();
        });
      });
      Promise.all([form1, form])
        .then(() => {
          var oDate1 = new Date(this.formData.serviceTimeStart);
          var oDate2 = new Date(this.formData.serviceTimeEnd);
          if (oDate1.getTime() > oDate2.getTime()) {
            this.$message.error("服务截止时间必须大于服务开始时间");
            return false;
          }
          this.addFuwu();
        })
        .catch(() => {
          app.util.validateRule(messageObj);
          this.btnDisable = false;
        });
    },

    async addFuwu() {
      //   通知服务方方式,如果都没有选中传数组字符串'0'
      if (this.newFormData.noticeApproches.length == 0) {
        this.newFormData.noticeApproches.push(0);
      }
      // 使用递归找出符合条件的数据需要
      const map = new Map();
      this.getLastItem(
        this.casOptions,
        this.newFormData.serviceScopeList,
        "objectId"
      );
      let serviceScopeListCopy = this.newFormData.serviceScopeList.slice();

      //递归出的数据会有重复,因为一个街道下面有两个社区的话就会循环push两遍,在这里去重
      this.newArr = this.sarr.filter(
        (v) => !map.has(v.objectId) && map.set(v.objectId, 1)
      );
      for (let i in this.newArr) {
        this.newFormData.serviceScopeList.push({
          objectId: this.newArr[i].objectId,
          objectType: this.newArr[i].objectType,
          objectName: this.newArr[i].objectName,
        });
      }
      this.newArr = [];
      //  如果是编辑的话回填的数据会有数组字符串需要将不是对象属性的过滤掉
      let arr = [];
      this.newFormData.serviceScopeList.forEach((item) => {
        if (typeof item != "string") {
          arr.push(item);
        }
      });
      this.newFormData.serviceScopeList = arr;
      try {
        let params = {
        title: this.formData.title,
        content: this.formData.content,
        commonServiceTypeId: this.formData.commonServiceTypeId,
        resiSearchTagId: this.formData.resiSearchTagId,
        assignFlag: this.formData.assignFlag,
        categoryCode:this.formData.categoryCode[1]?this.formData.categoryCode[1]:'',
        parentCategoryCode:this.formData.categoryCode[0]
      };

      if (this.formData.assignFlag === 1) {
        params.assignInfo = this.newFormData;
      }

      let url = "/governance/commonDemand/save";
      if (this.formType === "edit") {
        url = "/governance/commonDemand/update";
        params.id = this.scopeId;
      }
        const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        this.$message.success("添加成功");
        this.resetData();
        this.$emit("handleComfirm");
      }else{
        this.newFormData.serviceScopeList = serviceScopeListCopy
        this.$message.error(msg);
        console.log(msg);
      }
      }catch (error) {
        this.newFormData.serviceScopeList = serviceScopeListCopy
        this.$message.error(msg);
        console.log(msg);
        }
    },

    handleCancle() {
      this.resetData();
      this.$emit("handleClose");
    },

    resetData() {
      this.formData = {
        serviceTypeLevel1Id: "", // 公共服务（政策级别）一级分类id
        commonServiceTypeId: "", // 公共服务（政策级别）二级分类id
        assignFlag: 0,
        resiSearchTagId: "", //查找享受服务人员
        resiSearchTagName: "", //享受服务人员名称
        title: "", //服务名称
        assignInfo: {},
        content: "", //
      };
      this.newFormData = {
        noticeApproches: [],
        serviceScopeList: [], //
        serviceTimeStart: "", //服务起始时间yyyy-MM-dd
        serviceTimeEnd: "", //服务截止时间yyyy-MM-dd
        serverOrgType: "", //服务组织类型 社区自组织：community_org， 志愿者：ic_user_volunteer， 联建单位：party_unit
        serverOrgId: "", //服务组织Id
      };
    },
    // 开启加载动画
    startLoading() {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: "正在加载……", // 加载中需要显示的文字
        background: "rgba(0,0,0,.7)", // 背景颜色
      });
    },
    // 结束加载动画
    endLoading() {
      // clearTimeout(timer);
      if (loading) {
        loading.close();
      }
    },
  },
};
</script>
  
    <style lang="scss" scoped>
@import "@/assets/scss/modules/management/form-main.scss";
@import "@/assets/scss/modules/visual/a_customize.scss";

.form-item::v-deep .el-form-item__label {
  color: #fff;
}
.form-item {
  .el-radio {
    color: #fff;
  }

  .el-checkbox {
    color: #fff;
  }
}
.verifyRed::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.form_label_box {
  width: 150px;
  display: inline-block;
  text-align: right;
  padding-right: 12px;
}
</style>
  
