<template>
  <div>
    <el-card :class="{'box-card':source==='visiual'}">
      <el-form label-width="120px"
               :model="form"
               :rules="rules"
               ref="ruleForm">
        <el-form-item label="操作方式"
                      :class="{'form-item':source==='visiual'}"
                      prop="addType">
          <el-radio-group v-model="addType">
            <el-radio label="look">查看</el-radio>
            <template v-if="form.reportType != 'self_help'">
              <el-radio label="edit"
                        v-if="form.status === 'pending'">修改</el-radio>
              <el-radio label="cancel"
                        v-if="form.status !== 'finished' && form.status !== 'canceled'">取消</el-radio>
            </template>
            <el-radio label="appoint"
                      v-if="form.status === 'pending' || form.status === 'assigned'">指派</el-radio>
            <!-- <el-radio label="finish"
                    v-if="
              (form.reportType == 'self_help' &&
                form.serviceShowFlag &&
                form.serviceType !== 'volunteer' &&
                form.status !== 'finished') ||
              form.status === 'assigned' ||
              form.status === 'have_order' ||
              (form.status == 'finished' && !form.evaluateFlag)
            ">完成</el-radio> -->
            <el-radio label="finish"
                      v-if="
              (form.reportType == 'self_help' &&
                form.serviceShowFlag &&
                form.serviceType !== 'volunteer' &&
                form.status !== 'finished') ||
              form.status === 'assigned' ||
              form.status === 'have_order' 
            ">完成</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所属网格"
                      :class="{'form-item':source==='visiual'}"
                      prop="gridId">
          <div :class="{'visiual-form':source==='visiual'}">
            <el-input v-if="disabled"
                      v-model="form.gridName"
                      :disabled="disabled"
                      class="input-width"></el-input>
            <!-- <span >{{ form.gridName }}</span> -->
            <el-select v-else
                       v-model="form.gridId"
                       filterable
                       placeholder="请选择"
                       class="input-width"
                       clearable
                       :disabled="disabled"
                       @change="handleGridChange">
              <el-option v-for="item in disabled ? optionsG : optionsEditG"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="需求类型"
                      :class="{'form-item':source==='visiual'}"
                      prop="categoryCode">

          <div :class="{'visiual-form':source==='visiual'}">
            <el-input v-if="disabled"
                      v-model="form.categoryName"
                      :disabled="disabled"
                      class="input-width"
                      clearable></el-input>
            <el-cascader v-else
                         v-model="form.categoryCodeArr"
                         :options="demandOptions"
                         :disabled="disabled"
                         clearable
                         class="input-width"
                         @change="handleCateSlect"></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="上报类型"
                      :class="{'form-item':source==='visiual'}"
                      prop="reportType">

          <div :class="{'visiual-form':source==='visiual'}">
            <el-input v-if="disabled"
                      v-model="form.reportTypeName"
                      :disabled="disabled"
                      class="input-width"></el-input>
            <el-select v-else
                       v-model="form.reportType"
                       filterable
                       class="input-width"
                       placeholder="请选择"
                       clearable
                       :disabled="disabled">
              <el-option v-for="item in reportOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="上报人"
                      :class="{'form-item':source==='visiual'}"
                      prop="reportUserName">

          <div :class="{'visiual-form':source==='visiual'}">
            <el-input v-model="form.reportUserName"
                      :disabled="disabled"
                      placeholder="请输入"
                      class="input-width"
                      clearable></el-input>
          </div>
        </el-form-item>
        <el-form-item label="上报人手机号"
                      :class="{'form-item':source==='visiual'}"
                      prop="reportUserMobile">

          <div :class="{'visiual-form':source==='visiual'}">
            <el-input v-model="form.reportUserMobile"
                      :disabled="disabled"
                      placeholder="请输入"
                      class="input-width"
                      maxlength="11"
                      clearable></el-input>
          </div>
        </el-form-item>
        <el-form-item label="上报时间"
                      :class="{'form-item':source==='visiual'}"
                      prop="reportTime">

          <div :class="{'visiual-form':source==='visiual'}">
            <el-date-picker v-model="form.reportTime"
                            type="datetime"
                            class="input-width"
                            clearable
                            :disabled="disabled"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期时间">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="需求人"
                      :class="{'form-item':source==='visiual'}"
                      prop="demandUserId">

          <div :class="{'visiual-form':source==='visiual'}">
            <el-input v-if="disabled"
                      v-model="form.demandUserName"
                      :disabled="disabled"
                      class="input-width"></el-input>
            <el-select v-else
                       v-model="selectDemandUser"
                       class="input-width"
                       filterable
                       :disabled="disabled"
                       placeholder="请选择"
                       clearable
                       @change="handleDemandChange">
              <el-option v-for="item in demandUserList"
                         :key="item.demandUserId"
                         :label="item.label"
                         :value="item">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="服务时间"
                      :class="{'form-item':source==='visiual'}"
                      prop="wantServiceTime">

          <div :class="{'visiual-form':source==='visiual'}">
            <el-date-picker v-model="form.wantServiceTime"
                            type="datetime"
                            clearable
                            :disabled="disabled"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期时间">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="需求内容"
                      :class="{'form-item':source==='visiual'}"
                      prop="content">

          <div :class="{'visiual-form':source==='visiual'}">
            <el-input v-model="form.content"
                      :autosize="{ minRows: 2, maxRows: 10 }"
                      :disabled="disabled"
                      type="textarea"
                      clearable
                      class="cell-width-area"
                      placeholder="请输入内容"></el-input>
          </div>
        </el-form-item>
        <el-form-item v-if="
          addType === 'appoint' ||
          addType == 'finish' ||
          (addType == 'look' && form.serviceShowFlag)
        "
                      :class="{'form-item':source==='visiual'}"
                      label="服务方"
                      prop="serviceType">

          <div :class="{'visiual-form':source==='visiual'}">
            <template v-if="disabled && addType !== 'appoint'">
              <el-input v-model="form.serviceShowName"
                        :disabled="disabled"
                        class="input-width"></el-input>
            </template>
            <template v-else>
              <el-select v-model="form.serviceType"
                         class="input-width-small"
                         placeholder="请选择"
                         clearable
                         :disabled="disabled && addType !== 'appoint'"
                         @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="form.serverId"
                         class="input-width-middle"
                         filterable
                         placeholder="请选择"
                         clearable
                         :disabled="disabled && addType !== 'appoint'">
                <el-option v-for="item in serviceOptiondList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </template>
          </div>
        </el-form-item>
        <el-form-item v-if="addType == 'look' && form.status == 'canceled'"
                      label="取消时间"
                      :class="{'form-item':source==='visiual'}"
                      prop="cancelTime">
          <span>{{ form.cancelTime }}</span>
        </el-form-item>
        <template v-if="
          (addType == 'finish' && form.reportType != 'self_help') ||
          (addType == 'look' && form.status == 'finished')
        ">
          <el-form-item label="实际服务时间"
                        :class="{'form-item':source==='visiual'}"
                        prop="serviceStartTime">

            <div :class="{'visiual-form':source==='visiual'}">
              <el-date-picker v-model="finishServiceTime"
                              class="input-width-min"
                              clearable
                              :disabled="disabled && addType != 'finish'"
                              type="datetimerange"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              @change="handelBlurServiceTime">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="完成情况"
                        :class="{'form-item':source==='visiual'}"
                        prop="finishResult">
            <el-radio v-model="form.finishResult"
                      label="resolved"
                      :disabled="disabled && addType != 'finish'">已解决</el-radio>
            <el-radio v-model="form.finishResult"
                      label="unresolved"
                      :disabled="disabled && addType != 'finish'">未解决</el-radio>
          </el-form-item>
          <el-form-item label="评价"
                        prop="score"
                        :class="{'form-item':source==='visiual'}"
                        class="form-score">
            <el-rate v-model="form.score"
                     :allow-half="true"
                     :disabled="disabled && addType != 'finish'"></el-rate>
          </el-form-item>
          <el-form-item label="备注"
                        :class="{'form-item':source==='visiual'}"
                        prop="finishDesc">

            <div :class="{'visiual-form':source==='visiual'}">
              <el-input v-model="form.finishDesc"
                        :autosize="{ minRows: 2, maxRows: 10 }"
                        :disabled="disabled && addType != 'finish'"
                        type="textarea"
                        clearable
                        class="cell-width-area"
                        placeholder="请输入内容"></el-input>
            </div>
          </el-form-item>
        </template>
        <template v-if="addType == 'finish' && form.reportType == 'self_help'">
          <el-form-item label="实际服务时间"
                        :class="{'form-item':source==='visiual'}"
                        prop="serviceStartTime">

            <div :class="{'visiual-form':source==='visiual'}">
              <el-date-picker v-model="finishServiceTime"
                              class="input-width-min"
                              clearable
                              :disabled="disabled && addType != 'finish'"
                              type="datetimerange"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              @change="handelBlurServiceTime">
              </el-date-picker>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <!-- <div class="resi-btns">
        <el-button size="small"
                   @click="handlerClose">关闭</el-button>
        <el-button v-if="addType != 'look'"
                   type="primary"
                   size="small"
                   :loading="btnLoading"
                   @click="handleSubmit">提交</el-button>
      </div> -->

      <div v-if="source==='manage'"
           class="div-btn ">
        <el-button size="small"
                   @click="handlerClose">关闭</el-button>
        <el-button v-if="addType != 'look'"
                   style="margin-left:20px"
                   type="primary"
                   size="small"
                   @click="handleSubmit">提交</el-button>
      </div>
      <div v-else
           class="div-btn">
        <div class="item_btn"
             @click="handlerClose()">关闭</div>
        <div v-if="addType != 'look'"
             class="item_btn mgl"
             @click="handleSubmit()">提交</div>
      </div>
    </el-card>

  </div>
</template>

<script>
import { mapGetters } from "vuex";

export default {
  props: {
    demandRecId: {
      type: String,
      default: "",
    },
    // addType: {
    //   type: String,
    //   default: "look",
    // },
    source: {//展示来源：manage  管理平台    visiual  可视化平台
      type: String,
      default: 'visiual'
    }
  },

  data () {
    return {
      btnLoading: false,
      pageLoading: false,
      addType: 'look',
      form: {
        gridId: "",
        categoryCodeArr: [],
        categoryCode: "",
        parentCode: "",
        content: "",
        reportType: "",
        reportUserName: "",
        reportUserMobile: "",
        reportTime: "",
        wantServiceTime: "",
        demandUserId: "",
        demandUserName: "",
        demandUserMobile: "",
      },

      serviceOptions: [
        {
          label: "志愿者",
          value: "volunteer",
        },
        //  {
        //   label: '社会组织',
        //   value: 'social_org'
        // },
        {
          label: "社区自组织",
          value: "community_org",
        },
        {
          label: "区域党建单位",
          value: "party_unit",
        },
      ],
      serviceOptiondList: [],
      demandUserList: [],
      optionsEditG: [],
      reportOptions: [],
      demandOptions: [],
      selectDemandUser: "",
      finishServiceTime: "",

      options: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 2,
        },
      ],

      rules: {
        serviceStartTime: [
          { required: true, message: "实际服务时间不能为空", trigger: "blur" },
        ],
        score: [{ required: true, message: "评分不能为空", trigger: "blur" }],
        finishResult: [
          { required: true, message: "完成情况不能为空", trigger: "blur" },
        ],
      },
    };
  },

  computed: {
    ...mapGetters(["clientHeight", "iframeHeight"]),
    disabled () {
      return this.addType != "edit";
    },
  },

  watch: {
    addType (val) {
      this.formatRowForm(val);
    },
  },

  async created () {
    this.customerId = localStorage.getItem("customerId");

    this.getInfo();

    this.pageLoading = true;
  },

  methods: {
    filterEdit (id) {
      const { user } = this.$store.state;
      return id === user.agencyId;
    },
    handleCateSlect (val) {
      console.log("val", val);
      if (val.length === 1) {
        this.demandOptions.forEach((item) => {
          if (item.value == val[0]) this.form.parentCode = item.pvalue;
        });
        this.form.categoryCode = val[0];
      } else {
        this.form.parentCode = val[0];
        this.form.categoryCode = val[1];
      }
    },
    handleDemandChange (val) {
      console.log("val", val, this.selectDemandUser);
      this.selectDemandUser = val.label;
      this.form.demandUserName = val.demandUserName;
      this.form.demandUserMobile = val.demandUserMobile;
      this.form.demandUserId = val.demandUserId;
    },
    handelBlurServiceTime (val) {
      console.log("val", val);
      if (val.length > 0) {
        this.form.serviceStartTime = val[0];
        this.form.serviceEndTime = val[1];
      }
    },
    handleServiceChange (type, val) {
      if (val === "social_org") {
        if (type === "add") this.getServiceuserList(val, "add_demand");
        else this.getServiceuserList(val, "query_demand");
      } else this.getServiceuserList(val, "");
    },
    handleGridChange (val) {
      this.getDemandUserList();
    },

    handelBlurServiceTime (val) {
      console.log("val", val);
      if (val.length > 0) {
        this.form.serviceStartTime = val[0];
        this.form.serviceEndTime = val[1];
      }
    },

    handleServiceChange (type, val) {
      if (val === "social_org") {
        if (type === "add") this.getServiceuserList(val, "add_demand");
        else this.getServiceuserList(val, "query_demand");
      } else this.getServiceuserList(val, "");
    },

    handleAdd (addType) {
      this.addType = addType;
      this.dialogVisible = true;
    },

    handlerClose () {
      this.$emit("close");
    },

    async formatRowForm (addType) {
      this.addType = addType;
      const { form: row } = this;

      if (addType == "look") {
        this.finishServiceTime =
          (row.serviceStartTime && [
            row.serviceStartTime,
            row.serviceEndTime,
          ]) ||
          "";
      }
      if (addType == "finish") {
        if (row.serviceStartTime && row.serviceEndTime) {
          this.finishServiceTime = [row.serviceStartTime, row.serviceEndTime];

        } else {
          this.finishServiceTime = []
        }


        this.form.finishResult = "resolved";
        this.form.score = 5;
      }
      if (addType == "appoint" && row.serviceType) {
        const type = row.serviceType == "social_org" ? "add_demand" : "";
        await this.getServiceuserList(row.serviceType, type);
      }
      if (addType == "edit") {
        await this.getDemandUserList();
        this.demandOptions.forEach((item) => {
          if (item.value === row.categoryCode)
            this.form.categoryCode = [row.categoryCode];
        });
        this.demandUserList.forEach((item) => {
          if (item.demandUserId == row.demandUserId)
            this.selectDemandUser = item.label;
        });
      }

      this.dialogVisible = true;
    },

    async appointAjax () {
      const _form = {
        demandRecId: this.form.demandRecId,
        serviceType: this.form.serviceType,
        serverId: this.form.serverId,
      };
      await this.$http
        .post("/heart/userdemand/assign", _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.handlerClose();
            this.getInfo();
            this.$emit("success");
            return this.$message.success("指派成功");
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
      this.btnLoading = false;
    },

    async finishAjax () {
      const { reportType, serviceShowFlag, serviceType } = this.form;
      const _form = {
        demandRecId: this.form.demandRecId,
        serviceStartTime: this.form.serviceStartTime,
        serviceEndTime: this.form.serviceEndTime,
        finishResult: reportType == "self_help" ? "" : this.form.finishResult,
        finishDesc: reportType == "self_help" ? "" : this.form.finishDesc,
        serviceId: this.form.serviceId,
        score: reportType == "self_help" ? 0 : this.form.score,
      };
      await this.$http
        .post("/heart/userdemand/finish", _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.handlerClose();
            this.getInfo();
            this.$emit("success");
            return this.$message.success("操作成功");
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
      this.btnLoading = false;
    },

    async editCate () {
      const categoryCode = this.form.categoryCode;
      if (Array.isArray(categoryCode)) {
        if (categoryCode.length === 1) {
          this.demandOptions.forEach((item) => {
            if (item.value == categoryCode[0])
              this.form.parentCode = item.pvalue;
          });
          this.form.categoryCode = categoryCode[0];
        } else {
          this.form.parentCode = categoryCode[0];
          this.form.categoryCode = categoryCode[1];
        }
      }

      const _form = {
        ...this.form,
      };
      await this.$http
        .post("/heart/userdemand/update", _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.handlerClose();
            this.getInfo();
            this.$emit("success");
            return this.$message.success("修改成功");
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
      this.btnLoading = false;
    },

    handleSubmit () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.btnLoading = true;
          if (this.addType == "add") this.addNew();
          else if (this.addType == "edit") this.editCate();
          else if (this.addType == "appoint") this.appointAjax();
          else if (this.addType == "finish") this.finishAjax();
          else if (this.addType == "cancel") this.handleDel();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    handleDel () {
      let params = {
        demandRecId: this.demandRecId,
      };
      this.$http
        .post("/heart/userdemand/cancel", params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.$message.success("取消成功");
            this.getInfo();
            this.handlerClose();
            this.$emit("success");
          }
        })
        .catch((err) => {
          return this.$message.error("网络错误");
        });
    },

    getTreeData (data) {
      if (!Array.isArray(data)) return [];
      let arr = data.map((item) => {
        let _item = {};
        if (item.children) {
          if (item.children.length === 0)
            _item = { ...item, children: undefined };
          else _item = { ...item, children: this.getTreeData(item.children) };
        } else {
          _item = { ...item };
        }
        return _item;
      });
      return arr;
    },

    getFlagData (data, flag) {
      if (!Array.isArray(data)) return [];
      let arr1 = data.filter((item) => item[flag]);
      let arr2 = arr1.map((item) => {
        if (item.children)
          return { ...item, children: this.getFlagData(item.children, flag) };
        else return item;
      });
      // console.log('arrr-oppp', arr2)
      return arr2;
    },

    async getGridList (type, agencyId) {
      const { user } = await this.$store.state;
      console.log("user---ppp", user);
      // addorupdate  query
      await this.$http
        .post("/gov/org/customergrid/gridoption", {
          agencyId: agencyId || user.agencyId,
          purpose: type,
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            console.log("获取查询详情成功", res.data);

            if (type === "query") this.optionsG = res.data;
            else this.optionsEditG = res.data;
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },

    async getDemandUserList () {
      const { user } = await this.$store.state;
      console.log("user---ppp", user);
      const params = {
        agencyId: user.agencyId,
        gridId: this.form.gridId,
        name: "",
      };
      // addorupdate
      await this.$http
        .post("/epmetuser/icresiuser/demandusers", params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            console.log("获取查询详情成功", res.data);
            this.demandUserList = res.data;
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },

    async getDemandOptions () {
      this.$http
        .post("/heart/icresidemanddict/demandoption")
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.searchdemandOptions = this.getTreeData(res.data);
            this.demandOptions = this.getFlagData(
              this.getTreeData(res.data),
              "usableFlag"
            );
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },

    async getServiceuserList (serviceType, query) {
      if (!serviceType) return false;
      const { demandUserId } = this.form;
      const params = {
        serviceName: "",
        serviceType: serviceType,
        queryPurpose: query,
      };
      await this.$http
        .post("/heart/userdemand/servicelist", params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.serviceOptiondList = res.data.filter(
              (item) => item.value != demandUserId
            );
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },

    async getDictOptions () {
      this.$http
        .post("/sys/dict/data/dictlist", { dictType: "user_demand_status" })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.statusOptions = res.data;
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });

      this.$http
        .post("/sys/dict/data/dictlist", {
          dictType: "user_demand_report_type",
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.reportOptions =
              res.data && res.data.filter((item) => item.value != "self_help");
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });

      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 getInfo () {
      let params = {
        demandRecId: this.demandRecId,
      };
      await this.$http
        .post("/heart/userdemand/demandDetail", params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.form = {
              ...this.form,
              ...res.data,
              categoryCodeArr: [
                res.data.parentCode,
                res.data.parentCode + res.data.categoryCode,
              ],
            };

            this.finishServiceTime = [this.form.serviceStartTime, this.form.serviceEndTime]
            this.getGridList();
            this.getDemandOptions();
            this.getDemandUserList();
            this.getServiceuserList();
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/buttonstyle.scss";
@import "@/assets/scss/modules/visual/a_customize.scss";
@import "@/assets/scss/modules/shequzhili/event-info.scss";
</style>
