<template>
  <div v-if="pageLoading" class="g-main">
    <div class="m-search" ref="searchCard" style="flex-direction: column;">
      <section  :class="boxHeight ? 'm-form-box-height' : 'm-form-box-height-auto'">
        <el-form
        ref="searchForm"
        :inline="true"
        :model="searchForm"
        class="demo-form-inline"
        label-width="100px"
      >
        <el-form-item label="所属网格" prop="gridId">
          <el-select
            v-model.trim="searchForm.gridId"
            class="u-item-width-normal"
            size="small"
            filterable
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in optionsG"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              size="small"
              class="u-item-width-normal"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="需求分类" prop="categoryCode">
          <el-cascader
            v-model.trim="searchForm.categoryCode"
            class="u-item-width-daterange2"
            size="small"
            :options="searchdemandOptions"
            :props="{ checkStrictly: true,label: 'categoryName',value: 'categoryCode',children: 'childCateList'}"
            clearable
            @change="handleCateCHange"
          ></el-cascader>
          <!-- <el-select v-model.trim="searchForm.categoryCode" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="item in demandOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select> -->
        </el-form-item>
        <el-form-item label="需求人" prop="demandUserName">
          <el-input
            size="small"
            class="u-item-width-normal"
            v-model.trim="searchForm.demandUserName"
            placeholder="请输入内容"
            clearable=""
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            size="small"
            class="u-item-width-normal"
            v-model.trim="searchForm.status"
            filterable
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上报时间" prop="reportStartTime">
          <el-date-picker
            v-model.trim="reportTime"
            size="small"
            type="daterange"
            class="u-item-width-daterange2"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable=""
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select
            v-model.trim="searchForm.serviceType"
            class="u-item-width-normal"
            size="small"
            filterable
            placeholder="请选择"
            clearable
            @change="handleServiceChange('query', $event)"
          >
            <el-option
              v-for="item in serviceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="serverId">
          <el-select
            v-model.trim="searchForm.serverId"
            filterable
            :disabled="searchForm.serviceType ? false : true"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in serviceOptiondList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务时间" prop="wantServiceStartTime">
          <el-date-picker
            v-model.trim="serviceTime"
            size="small"
            class="u-item-width-daterange2"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      </section>
      <el-row>
        <el-col :span="24" align="right">
          <el-button type="primary" size="small" @click="handleSearch"
            >查询</el-button
          >
          <el-button
            class="diy-button--white"
            size="small"
            @click="resetForm('searchForm')"
            >重置</el-button
          >
          <!-- <el-button
              style="margin:0 6px 0 10px"
              size="small"
              class="div-table-button--blue"
              type="text"
              @click="boxHeight = !boxHeight"
              >{{ boxHeight ? "展开" : "收起"
              }}<i
                :class="boxHeight ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"
              ></i
            ></el-button> -->
        </el-col>
      </el-row>
    </div>

    <div class="m-table">
      <div class="div_btn">
      <el-button size="small" @click="handleAdd('add')" type="primary" icon="el-icon-plus"
        >新增</el-button
      >
    </div>
      <el-table
        :data="tableData"
        row-key="categoryId"
        v-loading="tableLoading"
        class="m-table-item"
        border
        :height="tableHeight"
        style="width: 100%"
      >
        <el-table-column label="序号" type="index" align="center" width="50">
        </el-table-column>
        <el-table-column
          v-for="item in tableHeader"
          :key="item.columnName"
          :prop="item.columnName"
          :label="item.label"
          :align="item.align"
          :min-width="item.width"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{ handleFilterSpan(scope.row, item) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <template >
              <el-button
                v-if="
                  scope.row.status === 'pending' ||
                  scope.row.status === 'assigned'
                "
                type="text"
                size="small"
                @click="handleAppoint(scope.row, 'appoint')"
                >指派</el-button
              >
              <!-- v-if="scope.row.status === 'assigned' || scope.row.status === 'have_order'" -->
              <template v-if="scope.row.status === 'assigned' || scope.row.status === 'have_order'">
                <el-button
                  v-if="scope.row.status !== 'finished'"
                  type="text"
                  size="small"
                  @click="handleFinish(scope.row, 'finish')"
                  >完成情况</el-button
                >
              </template>
              <template v-else>
                <el-button
                  v-if="
                    scope.row.status === 'assigned' ||
                    scope.row.status === 'have_order' ||
                    (scope.row.status == 'finished' && !scope.row.evaluateFlag)
                  "
                  type="text"
                  size="small"
                  @click="handleFinish(scope.row, 'finishNoEvaluate')"
                  >评价</el-button
                >
              </template>
              <template v-if="scope.row.reportType != 'self_help'">
                <el-button
                  v-if="scope.row.status === 'pending'"
                  @click="handleEdit(scope.row, 'edit')"
                  type="text"
                  size="small"
                  >修改</el-button
                >
                <el-popconfirm
                  title="取消之后无法恢复，确认取消？"
                  @onConfirm="handleDel(scope.row)"
                  style="margin-left: 10px;"
                >
                  <el-button
                    v-if="
                      scope.row.status !== 'finished' &&
                      scope.row.status !== 'canceled'
                    "
                    slot="reference"
                    type="text"
                    size="small"
                    >取消</el-button
                  >
                </el-popconfirm>
              </template>
            </template>
            <el-button
              @click="handleLook(scope.row, 'look')"
              type="text"
              size="small"
              style="margin-left: 10px;"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="pageSize"
        layout="sizes, prev, pager, next, total"
        :total="total"
      >
      </el-pagination>
    </div>
    </div>


    <el-dialog
      title="需求信息"
      :visible.sync="dialogVisible"
      width="50%"
      top="5vh"
      append-to-body
      class="dialog-h"
      :close-on-click-modal="false"
      :before-close="handlerCancle"
    >
      <el-form
        v-if="dialogVisible"
        label-width="130px"
        :model="form"
        :rules="rules"
        ref="ruleForm"
        class="form-wr dialog-h-content scroll-h"
      >
        <el-form-item label="所属网格" prop="gridId">
          <el-input
            v-if="disabled"
            v-model.trim="form.gridName"
            :disabled="disabled"
            size="small"
            class="input-width-small"
          ></el-input>
          <!-- <span >{{ form.gridName }}</span> -->
          <el-select
            v-else
            v-model.trim="form.gridId"
            filterable
            placeholder="请选择"
            size="small"
            class="input-width-small"
            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>
        </el-form-item>
        <el-form-item label="需求分类" prop="categoryCode">
          <el-input
            v-if="disabled"
            v-model.trim="form.categoryName"
            :disabled="disabled"
            class="input-width-min"
          ></el-input>
          <el-cascader
            v-else
            v-model.trim="form.categoryCode"
            :options="demandOptions"
            :props="{label: 'categoryName',value: 'categoryCode',children: 'childCateList'}"
            :disabled="disabled"
            clearable
            size="small"
            class="input-width-small"
            @change="handleCateSlect"
          ></el-cascader>
          <!-- <el-select v-model.trim="form.parentCode" filterable placeholder="请选择" class="input-width" clearable>
            <el-option
              v-for="item in demandOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="上报类型" prop="reportType">
          <el-input
            v-if="disabled"
            v-model.trim="form.reportTypeName"
            :disabled="disabled"
            class="input-width-small"
          ></el-input>
          <el-select
            v-else
            v-model.trim="form.reportType"
            filterable
            class="input-width-small"
            placeholder="请选择"
            clearable
            :disabled="disabled"
          >
            <el-option
              v-for="item in reportOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上报人" prop="reportUserName">
          <el-input
            v-model.trim="form.reportUserName"
            :disabled="disabled"
            placeholder="请输入"
            class="input-width-small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="上报人联系电话" prop="reportUserMobile">
          <el-input
            v-model.trim="form.reportUserMobile"
            :disabled="disabled"
            placeholder="请输入"
            class="input-width-small"
            maxlength="11"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="上报时间" prop="reportTime">
          <el-date-picker
            v-model.trim="form.reportTime"
            type="datetime"
            class="input-width-small"
            size="small"
            clearable
            :disabled="disabled"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="需求人" prop="demandUserId">
          <el-input
            v-if="disabled"
            v-model.trim="form.demandUserName"
            :disabled="disabled"
            class="input-width-small"
          ></el-input>
          <el-select
            v-else
            v-model.trim="form.demandUserId"
            class="input-width-small"
            filterable
            :disabled="disabled"
            placeholder="请选择"
            clearable
            @change="handleDemandChange"
            remote
            :remote-method="getDemandUserList"
          >
            <el-option
              v-for="item in demandUserList"
              :key="item.demanderId"
              :label="item.label"
              :value="item.demanderId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务时间" prop="wantServiceTime">
          <el-date-picker
            v-model.trim="form.wantServiceTime"
            type="datetime"
            class="input-width-small"
            clearable
            :disabled="disabled"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="需求内容" prop="content">
          <el-input
            v-model.trim="form.content"
            :autosize="{ minRows: 2, maxRows: 10 }"
            :disabled="disabled"
            type="textarea"
            clearable
            class="u-item-width-normal"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="
            addType === 'appoint' ||
            addType == 'finish' ||
            (addType == 'look' && form.serviceShowFlag)
          "
          label="服务组织"
          prop="serviceType"
        >
          <template v-if="disabled && addType !== 'appoint'">
            <el-input
              v-model.trim="form.serviceShowName"
              :disabled="disabled"
              class="u-item-width-normal"
            ></el-input>
          </template>
          <template v-else>
            <el-select
              v-model.trim="form.serviceType"
              class="u-item-width-normal"
              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.trim="form.serverId"
              class="u-item-width-normal"
              filterable
              placeholder="请选择"
              clearable
              :disabled="disabled && addType !== 'appoint'"
            >
              <el-option
                v-for="item in serviceOptiondList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item
          v-if="addType == 'look' && form.status == 'canceled'"
          label="取消时间"
          prop="cancelTime"
        >
          <span>{{ form.cancelTime }}</span>
        </el-form-item>
        <template
          v-if="
            (addType == 'finish' && form.reportType != 'self_help') ||
            (addType == 'look' && form.status == 'finished')||
            (addType == 'finishNoEvaluate' && !form.evaluateFlag)
          "
        >
          <el-form-item label="实际服务时间" prop="serviceStartTime">
            <el-date-picker
              v-model.trim="finishServiceTime"
              class="u-item-width-normal"
              clearable
              :disabled="disabled && addType != 'finish' || (addType === 'finishNoEvaluate')"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="handelBlurServiceTime"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="完成情况" prop="finishResult">
            <el-radio
              v-model.trim="form.finishResult"
              label="resolved"
              :disabled="disabled && addType != 'finish'"
              >已解决</el-radio
            >
            <el-radio
              v-model.trim="form.finishResult"
              label="unresolved"
              :disabled="disabled && addType != 'finish'"
              >未解决</el-radio
            >
          </el-form-item>
          <el-form-item label="评价" prop="score" class="form-score">
            <el-rate
              v-model.trim="form.score"
              :allow-half="true"
            ></el-rate>
          </el-form-item>
          <el-form-item
              label="上传图片"
              label-width="150px"
              style="display: block"
              prop="finishAttachments"
              v-if="addType != 'finishNoEvaluate'"
          >
            <UploadImages :fileList="form.finishAttachments" @change="(val) => form.finishAttachments = val" :limit="3"/>
          </el-form-item>
          <el-form-item
              label="上传图片"
              label-width="150px"
              style="display: block"
              prop="finishAttachments"
              v-else
          >
            <el-image :src="item.url" v-for="(item,index) in form.finishAttachments" :key="index" ></el-image>
          </el-form-item>
          <el-form-item label="备注" prop="finishDesc">
            <el-input
              v-model.trim="form.finishDesc"
              :autosize="{ minRows: 2, maxRows: 10 }"
              :disabled="disabled && addType != 'finish'"
              type="textarea"
              clearable
              class="input-width-textarea"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </template>
        <template v-if="addType == 'finish' && form.reportType == 'self_help'">
          <el-form-item label="实际服务时间" prop="serviceStartTime">
            <el-date-picker
              v-model.trim="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>
          </el-form-item>
        </template>
      </el-form>
      <div class="resi-btns">
        <el-button size="small" @click="handlerCancle">{{
          addType != "look" ? "取消" : "关闭"
        }}</el-button>
        <el-button
          v-if="addType != 'look'"
          type="primary"
          size="small"
          :loading="btnLoading"
          @click="handleSUbmit"
          >提交</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="需求详情"
      :visible.sync="detailShow"
      width="50%"
      top="5vh"
      append-to-body
      class="dialog-h"
      :close-on-click-modal="false"
      :before-close="detailFormCancle"
    >
      <detail ref="ref_form_detail" @diaDetailClose="detailFormCancle"></detail>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import info from "./info";
import detail from "./detail";
import { requestPost } from "@/js/dai/request";
import UploadImages from "@/components/UploadImages/UploadImages.vue"
export default {
  components: { info, detail,UploadImages },

  data() {
    return {
      tableLoading: false,
      btnLoading: false,
      disabled: false,
      pageLoading: false,
      dialogVisible: false,
      currentPage: 1,
      pageSize:20,
      total: null,
      tableData: [],
      searchH: 0,
      addLevel: "1",
      addType: "add",
      value: "",
      statusOptions: [
        {
          label: "待处理",
          value: "pending",
        },
        {
          label: "已取消",
          value: "canceled",
        },
        {
          label: "已指派",
          value: "assigned",
        },
        {
          label: "已接单",
          value: "have_order",
        },
        {
          label: "已完成",
          value: "finished",
        },
      ],

      boxHeight:true,

      serviceOptions: [

      ],
      serviceOptiondList: [],
      options: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 2,
        },
      ],
      reportOptions: [],
      demandOptions: [],
      searchdemandOptions: [],
      demandUserList: [],
      optionsG: [],
      optionsEditG: [],
      tableHeader: [
        {
          label: "状态",
          align: "center",
          columnName: "statusName",
          width: "120",
          options: [
            {
              label: "待处理",
              value: "pending",
            },
            {
              label: "已取消",
              value: "canceled",
            },
            {
              label: "已派单",
              value: "assigned",
            },
            {
              label: "已接单",
              value: "have_order",
            },
            {
              label: "已完成",
              value: "finished",
            },
          ],
        },
        {
          label: "所属网格",
          columnName: "gridName",
          align: "center",
          width: "",
          options: [],
        },
        {
          label: "需求类型",
          columnName: "categoryAllName",
          align: "center",
          width: "",
          options: [],
        },
        {
          label: "需求内容",
          columnName: "content",
          align: "center",
          width: "",
          options: [],
        },
        {
          label: "上报类型",
          columnName: "reportTypeName",
          align: "center",
          width: "120",
          options: [
            {
              label: "社区帮办",
              value: "community",
            },
            {
              label: "楼长帮办",
              value: "building_caption",
            },
            {
              label: "党员帮办",
              value: "party",
            },
            {
              label: "自身上报",
              value: "self_help",
            },
          ],
        },
        {
          label: "上报人",
          columnName: "reportUserName",
          align: "center",
          width: "120",
          options: [],
        },
        {
          label: "上报时间",
          columnName: "reportTime",
          align: "center",
          width: "180",
          options: [],
        },
        {
          label: "需求人",
          columnName: "demandUserName",
          align: "center",
          width: "80",
          options: [],
        },
        {
          label: "服务组织",
          columnName: "serviceShowName",
          align: "center",
          width: "120",
          options: [],
        },
        {
          label: "服务时间",
          columnName: "wantServiceTime",
          align: "center",
          width: "180",
          options: [],
        },
      ],
      customerId: "",
      reportTime: "",
      serviceTime: "",
      finishServiceTime: "",
      searchForm: {
        gridId: "",
        categoryCode: "",
        level: "",
        demandUserName: "",
        reportStartTime: "",
        reportEndTime: "",
        status: "",
        serviceType: "",
        serverId: "",
        wantServiceStartTime: "",
        wantServiceEndTime: "",
      },
      selectDemandUser: "",
      form: {
        gridId: "",
        categoryCode: "",
        parentCode: "",
        content: "",
        reportType: "",
        reportUserName: "",
        reportUserMobile: "",
        reportTime: "",
        wantServiceTime: "",
        demandUserId: "",
        demandUserName: "",
        demandUserMobile: "",
        finishAttachments:[]
      },
      rules: {
        gridId: [
          { required: true, message: "所属网格不能为空", trigger: "blur" },
        ],
        categoryCode: [
          { required: true, message: "需求分类不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "需求内容不能为空", trigger: "blur" },
        ],
        reportType: [
          { required: true, message: "上报类型不能为空", trigger: "blur" },
        ],
        reportUserName: [
          { required: true, message: "上报人不能为空", trigger: "blur" },
        ],
        reportUserMobile: [
          {
            required: true,
            message: "上报人联系电话不能为空",
            trigger: "blur",
          },
        ],
        reportTime: [
          { required: true, message: "上报时间不能为空", trigger: "blur" },
        ],
        demandUserId: [
          { required: true, message: "需求人不能为空", trigger: "blur" },
        ],
        wantServiceTime: [
          { required: true, message: "服务时间不能为空", trigger: "blur" },
        ],
        serviceType: [
          { required: true, message: "服务组织不能为空", trigger: "blur" },
        ],
        serviceStartTime: [
          { required: true, message: "实际服务时间不能为空", trigger: "blur" },
        ],
        score: [{ required: true, message: "评分不能为空", trigger: "blur" }],
        // finishDesc: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
        finishResult: [
          { required: true, message: "完成情况不能为空", trigger: "blur" },
        ],
      },

      visitableInfo: false,
      currDemandId: "",
      infoAddType: "look",
      detailShow: false,
      detailObj:{}
    };
  },
  computed: {
    ...mapGetters(["clientHeight", "iframeHeight"]),
    tableHeight() {
      const h = this.clientHeight - this.searchH - 445 + this.iframeHeigh;
      const _h = this.clientHeight - 445 - this.searchH;
      return this.$store.state.inIframe ? h : _h;
    },
  },
  async created() {
    this.customerId = localStorage.getItem("customerId");

    this.getTableData();
    this.getDemandOptions();
    this.getDictOptions();
    setTimeout(() => {
      this.getGridList("query");
      this.getGridList("addorupdate");
    }, 200);
    this.pageLoading = true;
  },
  mounted() {
    this.$nextTick(() => {
      this.searchH = this.$refs.searchCard.$el.offsetHeight;
      console.log("tableHeight", this.tableHeight);
    });
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getTableData();
    },
    handleFilterSpan(row, item) {
      let _val = "";
      if (item.options && item.options.length > 0) {
        item.options.forEach((n) => {
          if (n.value === row[item.columnName]) _val = n.label;
        });
      }
      return _val || row[item.columnName];
    },
    filterEdit(id) {
      const { user } = this.$store.state;
      return id === user.agencyId;
    },
    resetForm(formName) {
      this.searchForm.reportStartTime = "";
      this.searchForm.reportEndTime = "";
      this.searchForm.wantServiceStartTime = "";
      this.searchForm.wantServiceEndTime = "";
      this.searchForm.categoryCode = "";
      this.searchForm.level = "";
      this.reportTime = "";
      this.serviceTime = "";
      this.$refs[formName].resetFields();
      this.handleSearch();
    },
    handleCateCHange(val) {
      console.log("val", val);
      this.searchForm.categoryCode = val[1] || val[0];
      this.searchForm.level = val.length;
    },
    handleCateSlect(val) {
      console.log("val", val);
      if (val.length === 1) {
        this.form.parentCode = val[0];
        this.form.categoryCode = '';
      } 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.demanderName;
      this.form.demandUserMobile = val.demanderMobile;
    //   this.form.demandUserId = val.demanderId;
    },
    handleSearch(val) {
      console.log("searchhh--", val);
      this.currentPage = 1;
      if (Array.isArray(this.reportTime) && this.reportTime.length > 0) {
        this.searchForm.reportStartTime = this.reportTime[0];
        this.searchForm.reportEndTime = this.reportTime[1];
      }
      if (Array.isArray(this.serviceTime) && this.serviceTime.length > 0) {
        this.searchForm.wantServiceStartTime = this.serviceTime[0];
        this.searchForm.wantServiceEndTime = this.serviceTime[1];
      }
      this.getTableData();
    },
    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();
    },
    handleAdd(addType) {
      this.addType = addType;
      this.dialogVisible = true;
    },
    handlerCancle() {
      // this.form.categoryCode = ''
      // this.form.parentCode = ''
      // this.form.demandUserName = ''
      // this.form.demandUserMobile = ''
      // this.form.demandUserId = ''
      this.$delete(this.form, "demandRecId");
      this.selectDemandUser = "";
      this.finishServiceTime = "";
      for (const n in this.form) {
        this.form[n] = "";
      }
      this.disabled = false;
      // this.$refs.ruleForm.resetFields()
      this.dialogVisible = false;
    },
    //然后在这里处理相当于initForm
    async formatRowForm(row, addType, disabled) {
      this.form = { ...row, categoryCode: [row.parentCode, row.categoryCode] };
      this.addType = addType;

      if (disabled) {
        // await this.getGridList('query', row.agencyId)
        this.disabled = disabled;
      }
      if (addType == "look") {
        this.finishServiceTime =
          (row.serviceStartTime && [
            row.serviceStartTime,
            row.serviceEndTime,
          ]) ||
          "";
      }
      if (addType == "finish") {
        if (row.serviceStartTime)
          this.finishServiceTime = [row.serviceStartTime, row.serviceEndTime];
          this.form.finishResult = "resolved";
          this.form.score = 5;
      }
      if(addType == 'finishNoEvaluate'){
        this.finishServiceTime = [row.serviceStartTime, row.serviceEndTime];
        this.form.finishResult = row.finishResult;
        this.form.finishDesc = row.finishDesc;
        this.form.finishAttachments = row.finishAttachments;
      }
      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.form.categoryCode = [row.parentCode,row.categoryCode];
        this.demandUserList.forEach((item) => {
          if (item.demandUserId == row.demandUserId)
            this.selectDemandUser = item.label;
        });
      }

      this.dialogVisible = true;
    },
    async handleLook(row, type) {
      this.detailShow = true;
      this.$nextTick(() => {
        this.$refs.ref_form_detail.initForm(row);
      });
      // await this.formatRowForm(row, type, true);
    },

    detailFormCancle() {
      this.detailShow = false;
    },
    //这个是点击指派要的form
    async handleAppoint(row, type) {
      await this.formatRowForm(row, type, true);
    },
    async handleFinish(row, type) {
      await this.formatRowForm(row, type, true);
    },
    async handleEdit(row, type) {
      await this.formatRowForm(row, type, false);
      // this.form = { ...row, categoryCode: [row.parentCode, row.categoryCode] }
      // this.addType = addType
      // this.demandOptions.forEach(item => {
      //   if (item.value === row.categoryCode) this.form.categoryCode = [row.categoryCode]
      // })
      // await this.getDemandUserList()
      // this.demandUserList.forEach(item => {
      //   if (item.demandUserId == row.demandUserId) this.selectDemandUser = item
      // })
      // console.log('selectDemandUser', this.selectDemandUser)
      // this.dialogVisible = true
    },
    formatRowForm2(row, type) {
      this.visitableInfo = true;
      this.currDemandId = row.demandRecId;
      this.infoAddType = type;
    },
    async addNew() {
      const _form = {
        ...this.form,
      };
      // 需求上去掉了图片，但是我又不会改代码，先赋值为[]
      _form.finishAttachments = [];
      await this.$http
        .post("/governance/userdemand/add", _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.handlerCancle();
            this.getTableData();
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
      this.btnLoading = false;
    },
    async appointAjax() {
      const _form = {
        demandRecId: this.form.demandRecId,
        serviceType: this.form.serviceType,
        serverId: this.form.serverId,
      };
      await this.$http
        .post("/governance/userdemand/assign", _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.handlerCancle();
            this.getTableData();
          }
        })
        .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,
        finishAttachments: this.form.finishAttachments
      };
      // console.log(_form,'_form')
      // return
      await this.$http
        .post("/governance/userdemand/finish", _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.handlerCancle();
            this.getTableData();
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
      this.btnLoading = false;
    },
    async editCate() {
      const categoryCode = this.form.categoryCode;
      if (Array.isArray(categoryCode)) {
          this.form.parentCode = categoryCode[0];
          this.form.categoryCode = categoryCode[1]? categoryCode[1]:'';
      }

      const _form = {
        ...this.form,
      };
      await this.$http
        .post("/governance/userdemand/update", _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.handlerCancle();
            this.getTableData();
          }
        })
        .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 {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleDel(row) {
      let params = {
        demandRecId: row.demandRecId,
      };
      console.log("row1", row);
      this.$http
        .post("/governance/userdemand/cancel", params)
        .then(({ data: res }) => {
          console.log("row2", row);
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            console.log("row3", row);
            this.$message.success("取消成功");
            this.getTableData();
          }
        })
        .catch((err) => {
          console.log("row4", err);
          return this.$message.error("网络错误");
        });
    },
    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;
    },
    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;
    },
    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(demanderName) {
      const { user } = await this.$store.state;
      console.log("demanderName:", demanderName);
      // addorupdate
      await this.$http
        .get(`/actual/base/resiDemand/listDemander2Serve?gridId=${this.form.gridId}&demanderName=${demanderName ? demanderName : ''}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            console.log("获取查询详情成功", res.data);
            res.data.map(e=>{
                e.label = e.demanderName + "(" + e.demanderMobile + ")";
            })
            this.demandUserList = res.data;
          }
        })
        .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.searchdemandOptions = this.getTreeData(res.data);
            this.demandOptions = this.getFlagData(
              this.getTreeData(res.data),
              "usableFlag"
            );
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },
    //这是回填包括点击时调的接口真乱啊
    async getServiceuserList(serviceType, query) {
      const url = "/actual/base/serviceitem/listServerOrgNewTask";
      let params = {
        serverOrgCategoryCode: this.form.categoryCode[1],
        serverParentOrgCategoryCode:this.form.categoryCode[0],
        serverOrgType: serviceType,
      };
      let { data, code, msg } = await requestPost(url, params);
      if (code == 0) {
        this.serviceOptiondList = data;
      } else if (code >= 8000) {
        this.$message.error(msg);
      }
    },
    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.filter(item=>item.value != 'fifteen_mins_places');
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
    },
    async getTableData() {
      this.tableLoading = true;
      let params = {
        ...this.searchForm,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
      };
      await this.$http
        .post("/governance/userdemand/pagelist", params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.tableData = res.data.list;
            this.total = res.data.total;
          }
        })
        .catch(() => {
          return this.$message.error("网络错误");
        });
      this.tableLoading = false;
    },

  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/modules/management/list-main.scss";
.resi-container .resi-card-table {
  ::v-deep .el-table th {
    color: #fff;
    background-color: rgba(33, 149, 254, 1);
    // border-right: 1px solid rgba(33, 149, 254, 1);
  }
}
.resi-table {
  // ::v-deep .el-button--text {
  //   text-decoration: underline;
  // }
  ::v-deep .btn-color-del {
    margin: 0 10px;
    color: rgba(213, 16, 16, 1);
  }
  ::v-deep .btn-color-edit {
    color: rgba(0, 167, 169, 1);
  }
}
.form-wr {
  .input-width-small {
    width: 260px;
    &-small {
      width: 160px;
    }
    &-middle {
      width: 200px;
    }
    &-min {
      min-width: 260px;
    }
  }
  .input-width-textarea {
    width: 400px;
  }
  .form-score {
    ::v-deep .el-rate {
      margin-top: 8px;
    }
  }
}
</style>

<style lang="scss" scoped>
.resi-row-btn {
  display: flex;
  margin-bottom: 13px;
  ::v-deep .el-button {
    // margin-left: 10px;
    border: 0;
  }
  ::v-deep .el-select {
    margin-right: 10px;
  }
  .el-button--success {
    background: rgba(34, 193, 195, 1);
  }
}
.avatar-uploader {
  ::v-deep .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409eff;
  }
  .avatar {
    width: 70px;
    height: 70px;
    display: block;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 70px;
    height: 70px;
    line-height: 70px;
    text-align: center;
  }
}

.resi-btns {
  margin-top: 20px;
  text-align: center;
}
</style>
