<template>
  <div>
    <div
      class="dialog-h-content scroll-h"
      :class="{ 'visiual-form': source === 'visiual' }"
    >
      <el-form
        v-if="formType === 'add' || formType == 'edit'"
        ref="ref_form"
        :inline="true"
        :model="formData"
        :rules="dataRule"
        class="div_form"
      >
        <!-- 服务类别 -->
        <el-form-item
          label="姓名"
          style="display: block"
          label-width="150px"
          prop="name"
        >
        <el-input
            class="input-width-small"
            placeholder="请输入姓名"
            v-model="formData.name"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="性别"
          prop="gender"
          label-width="150px"
          :class="{ 'form-item': source === 'visiual' }"
          style="display: block"
        >
          <el-select
            v-model="formData.gender"
            class="input-width-small"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in genderArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          </el-form-item>
         <el-form-item
          label="出生日期"
          label-width="150px"
          :class="{ 'form-item': source === 'visiual' }"
          prop="birthday"
        >
          <el-date-picker
            v-model="formData.birthday"
            class="item_width_2"
            style="width: 220px"
            type="date"
            value-format="yyyy-MM-dd"
            value="yyyy-MM-dd"
            placeholder="出生日期"
          >
          </el-date-picker>
      
        </el-form-item>
        <el-form-item
          label="民族"
          prop="nation"
          label-width="150px"
          :class="{ 'form-item': source === 'visiual' }"
          style="display: block"
        >
          <el-select
            v-model="formData.nation"
            class="input-width-small"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in nationArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          </el-form-item>
          <el-form-item
          label="证件号"
          style="display: block"
          label-width="150px"
          prop="idCard"
        >
        <el-input
            class="input-width-small"
            placeholder="请输入证件号"
            v-model="formData.idCard"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="联系电话"
          style="display: block"
          label-width="150px"
          prop="phone"
        >
        <el-input
            class="input-width-small"
            placeholder="请输入联系电话"
            v-model="formData.phone"
          >
          </el-input>
        </el-form-item>
        
        <el-form-item label="文化程度" prop="eduLevel">
            <el-select
              class="u-item-width-normal"
              v-model="formData.eduLevel"
              placeholder="全部"
              size="small"
              clearable
            >
              <el-option
                v-for="item in eduArray"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        <el-form-item
          label="政策依据"
          prop="policyId"
          label-width="150px"
          :class="{ 'form-item': source === 'visiual' }"
          style="display: block"
        >
          <el-select
            v-model="formData.policyId"
            class="input-width-small"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in policyList"
              :key="item.policyId"
              :label="item.title"
              :value="item.policyId"
            >
            </el-option>
          </el-select>

          <!-- <el-button
              style="margin-left: 10px"
              type="primary"
              size="small"
              @click="handlePersonList"
              >预览</el-button
            > -->
        </el-form-item>

        <el-form-item
          label="经办人"
          prop="principalName"
          :class="{ 'form-item': source === 'visiual' }"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            placeholder="请输入联系人姓名"
            v-model="formData.principalName"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="联系方式"
          prop="principalContact"
          :class="{ 'form-item': source === 'visiual' }"
          label-width="150px"
          style="display: block"
        >
          <el-input
            class="item_width_1"
            placeholder="请输入联系人电话"
            v-model="formData.principalContact"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="指派服务" label-width="150px">
          <el-switch
            v-model="formData.assignSwitch"
            @change="handelDisabledRules"
          >
          </el-switch>
        </el-form-item>

        <el-form-item
          label="查找享受服务人员"
          prop="resiSearchTagId"
          :class="{ 'form-item': source === 'visiual' }"
          label-width="150px"
          style="display: block"
          v-if="formData.assignSwitch"
        >
          <input
            type="text"
            v-model="formData.resiSearchTagId"
            v-show="false"
          />
          <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="服务组织"
          prop="serviceOrgId"
          label-width="150px"
          :class="{ 'form-item': source === 'visiual' }"
          style="display: block"
        >
          <el-select
            v-model="formData.serviceOrgType"
            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="formData.serviceOrgId"
            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
          label="直接反馈"
          prop="remark"
          label-width="150px"
          :class="{ 'form-item': source === 'visiual' }"
          style="display: block"
        >
          <el-checkbox
            :label="'是'"
            v-model="showFeedback"
            @change="handleChangeFeedback"
          ></el-checkbox>
        </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>
  </div>
</template>
  
    <script>
import { Loading } from "element-ui"; // 引入Loading服务
import { requestPost, requestGet } from "@/js/dai/request";
//   import personList from "../policy/personList";
import nextTick from "dai-js/tools/nextTick";
//   import labelForm from "../labelConfig/addForm.vue";
import { computedCard } from '@/utils/index'

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

export default {
  props: {
   
    serviceRecordId: {
      type: String,
      required: "",
    },
    serviceCategoryKey: {
      type: String,
      required: "",
    },
   
    formType: {
      //表单操作类型 add新增，edit编辑，detail详情,feedback反馈
      type: String,
      required: "",
    },
   
    source: {
      //展示来源：manage  管理平台    visiual  可视化平台
      type: String,
      default: "manage",
    },
  },

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

    return {
      // 公共服务分类
      serviceTypesLevel1: [],
      serviceTypesLevel2: [],

      btnDisable: false,
      casOptions: [],
      scopeIdArray: [],
      iscascaderShow: 0,

      optionProps: {
        multiple: true,
        value: "objectId",
        label: "objectName",
        children: "children",
        checkStrictly: true,
        emitPath: false,
      },

      formData: {
      
      },
    
      genderArr:[
        {label:'男',value:'1'},
        {label:'女',value:'2'},
      ],
      nationArr:[],
      // endPickerOptions: {
      //   disabledDate: endDisabledDate,
      // },
      // startPickerOptions: {
      //   disabledDate: startDisabledDate,
      // },

      showFeedback: false,
      serviceOptions: [],
      serviceOptiondList: [],
      policyList: [],

      fileList: [],
      uploadUlr: window.SITE_CONFIG["apiURL"] + "/oss/file/uploadvariedfile",

      policyId: "",
      showPersonList: false,
      ruleList: [],
      firstInitMap: true,

      categrayOptions: [],
    

      showLabelForm: false,
    };
  },

  computed: {
    
    dataRule() {
      return {
        // serviceTypeLevel2Id: [
        //   { required: true, message: "政策类型不能为空", trigger: "change" },
        // ],
        // serviceName: [
        //   { required: true, message: "服务名称不能为空", trigger: "change" },
        // ],
        // serviceOrgId: [
        //   { required: true, message: "服务组织不能为空", trigger: "change" },
        // ],

        // serviceTimeStart: [
        //   { required: true, message: "服务时间不能为空", trigger: "change" },
        // ],
        // objList: [
        //   { required: true, message: "服务范围不能为空", trigger: "change" },
        // ],
        // resiSearchTagId: [
        //   {
        //     required: true,
        //     message: "享受服务人员不能为空",
        //     trigger: "change",
        //   },
        // ],
      };
    },
  },

  watch: {
   
  },

  components: {},

  async mounted() {
    this.startLoading();
    // 都已经重置了，还放在prop里干嘛，我不理解

    this.getDictOptions();

    if (this.formType === "add") {
      // await this.loadScopeTree();
    } else {
    }


    this.endLoading();
    // 服务分类下拉（其实是获取的共性服务分类）
  },

  methods: {
   

    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 = "";
    },
    

    //加载组织数据
    async handlePersonList() {
      if (!this.formData.policyId) {
        this.$message.info("请先选择政策");
        return false;
      }

      this.policyId = this.formData.policyId;
      await this.loadRuleList();

      this.showPersonList = true;
    },

    async loadRuleList() {
      const url = "/governance/policy/rulelist/" + this.policyId;

      let params = {};

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

      if (code === 0) {
        this.ruleList = data;
      } else {
        this.$message.error(msg);
      }
    },

    handleClose() {
      this.showPersonList = false;
    },
    handleOk() {
      this.showPersonList = false;
    },

    
    //字典
    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;
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },

   
    
    //字典
    async getServiceuserList(serverOrgType) {
      
      const url = "/actual/base/serviceitem/listServerOrg";
      let params = {
        serviceTypeId: this.formData.serviceTypeLevel2Id,
        serverOrgType: serverOrgType,
        businessType: "common_service",
      };
      let { data, code, msg } = await requestPost(url, params);
      if (code == 0) {
        this.serviceOptiondList = data;
      } else if (code >= 8000) {
        this.$message.error(msg);
      }
    },
   
    async handleComfirm() {
      if (this.formType === "add") {
        this.handleAdd();
      } else if (this.formType === "feedback") {
        this.handleFeedback();
      }
    },

    async handleAdd() {
      this.btnDisable = true;
      setTimeout(() => {
        this.btnDisable = false;
      }, 10000);
      this.$refs["ref_form"].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj);
          this.btnDisable = false;
        } else {
            this.addFuwu();
        }
      });
    },

    async addFuwu() {
     
      console.log(this.formData);
      // return false
      const regPhone = /^1(3|4|5|6|7|8|9)\d{9}$/; //联系电话

      if (
        this.formData.principalContact &&
        regPhone.test(this.formData.principalContact) === false
      ) {
        this.btnDisable = false;
        this.$message({
          type: "warning",
          message: "请输入正确的联系电话",
        });
        return false;
      }
     
      const url = "/governance/icServiceRecordV2/add";
      // const url = 'http://yapi.elinkservice.cn/mock/245/governance/icServiceProject/service/initiate'
      let params = {
        ...this.formData,
      };
      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        this.$message.success("发起成功");
        this.resetData();
        this.$emit("handleOk");
      } else {
        this.$message.error(msg);
      }
    },

    async handleFeedback() {
      this.btnDisable = true;
      setTimeout(() => {
        this.btnDisable = false;
      }, 10000);

      this.$refs["ref_form_feedback"].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj);
          this.btnDisable = false;
        } else {
          this.addFeecback();
        }
      });
    },

    async addFeecback() {
      this.feedbackFormData.fileList = [];
      this.feedbackFormData.fileList = [...this.fileList];
      this.feedbackFormData.serviceRecordId = this.serviceRecordId;

      console.log(this.feedbackFormData);
      // return false

      const url = "/governance/icServiceFeedbackV2/add";

      let params = {
        ...this.feedbackFormData,
      };

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

      if (code === 0) {
        this.$message.success("反馈成功");
        this.resetData();
        this.$emit("handleOk");
      } else {
        this.$message.error(msg);
      }
    },

    resetData() {
      this.formData = {
        serviceTypeLevel1Id: "", // 公共服务（政策级别）一级分类id
        serviceTypeLevel2Id: "", // 公共服务（政策级别）二级分类id
        objList: [], //
        principalName: "", //经办人(责任人)姓名
        principalContact: "", //经办人联系方式
        serviceTimeStart: "", //服务起始时间yyyy-MM-dd
        serviceTimeEnd: "", //服务截止时间yyyy-MM-dd
        remark: "", //
        feedback: {}, //反馈。允许发起服务的时候直接填写反馈，完成服务。
      };
      this.feedbackFormData = {
        serviceGoal: "", //	服务目标
        serviceEffect: "", //	服务效果
        servicePeopleNumber: null, //	服务人数
        serviceStatus: "completed", //	服务状态。in_service服务中；completed:已完成
        satisfaction: "", //满意度。不满意:bad、基本满意:good、非常满意:perfect
        longitude: "", //	经度
        latitude: "", //	维度
        address: "",
        fileList: [], //	附件列表
      };
    },
    // 开启加载动画
    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;
  }
}
</style>
  