<template>
  <div v-if="pageLoading"
       class="resi-container">
    <el-card ref="searchCard"
             class="search-card">
      <div>
        <el-form ref="searchForm"
                 :inline="true"
                 :model="searchForm"
                 class="demo-form-inline"
                 label-width="80px">
          <div>
            <el-form-item label="所属网格"
                          prop="gridId">
              <el-select v-model="searchForm.gridId"
                         filterable
                         placeholder="请选择"
                         clearable>
                <el-option v-for="item in optionsG"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="需求分类"
                          prop="categoryCode">
              <el-cascader v-model="searchForm.categoryCode"
                           :options="searchdemandOptions"
                           :props="{ checkStrictly: true }"
                           clearable
                           @change="handleCateCHange"></el-cascader>
              <!-- <el-select v-model="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 v-model="searchForm.demandUserName"
                        placeholder="请输入内容"
                        clearable=""></el-input>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="状态"
                          prop="status">
              <el-select v-model="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="reportTime"
                              type="daterange"
                              format="yyyy 年 MM 月 dd 日"
                              value-format="yyyy-MM-dd"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              clearable="">
              </el-date-picker>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="服务类型"
                          prop="serviceType">
              <el-select v-model="searchForm.serviceType"
                         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="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="serviceTime"
                              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-item>
              <el-button class="diy-button--search"
                         size="small"
                         @click="handleSearch">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button class="diy-button--reset"
                         size="small"
                         @click="resetForm('searchForm')">重置</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>
    <el-card class="resi-card-table">
      <div class="resi-row-btn">
        <el-button class="diy-button--add"
                   size="small"
                   @click="handleAdd('add')">新增</el-button>
      </div>

      <el-table :data="tableData"
                row-key="categoryId"
                v-loading="tableLoading"
                border
                :height="tableHeight"
                style="width: 100%"
                class="resi-table">
        <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 v-if="filterEdit(scope.row.agencyId)">
              <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.reportType == 'self_help' &&
                  scope.row.serviceShowFlag
                ">
                <el-button v-if="
                    scope.row.serviceType !== 'volunteer' &&
                    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, 'finish')">完成情况</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"
                           class="btn-color-edit">修改</el-button>
                <el-popconfirm title="取消之后无法恢复，确认取消？"
                               @onConfirm="handleDel(scope.row)">
                  <el-button v-if="
                      scope.row.status !== 'finished' &&
                      scope.row.status !== 'canceled'
                    "
                             slot="reference"
                             type="text"
                             size="small"
                             class="btn-color-del">取消</el-button>
                </el-popconfirm>
              </template>
            </template>
            <el-button @click="handleLook(scope.row, 'look')"
                       type="text"
                       size="small"
                       class="btn-color-look">查看</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>
    </el-card>

    <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="120px"
               :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="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>
        </el-form-item>
        <el-form-item label="需求类型"
                      prop="categoryCode">
          <el-input v-if="disabled"
                    v-model="form.categoryName"
                    :disabled="disabled"
                    class="input-width-min"></el-input>
          <el-cascader v-else
                       v-model="form.categoryCode"
                       :options="demandOptions"
                       :disabled="disabled"
                       clearable
                       class="input-width"
                       @change="handleCateSlect"></el-cascader>
          <!-- <el-select v-model="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="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>
        </el-form-item>
        <el-form-item label="上报人"
                      prop="reportUserName">
          <el-input v-model="form.reportUserName"
                    :disabled="disabled"
                    placeholder="请输入"
                    class="input-width"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="上报人手机号"
                      prop="reportUserMobile">
          <el-input v-model="form.reportUserMobile"
                    :disabled="disabled"
                    placeholder="请输入"
                    class="input-width"
                    maxlength="11"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="上报时间"
                      prop="reportTime">
          <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>
        </el-form-item>
        <el-form-item label="需求人"
                      prop="demandUserId">
          <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>
        </el-form-item>
        <el-form-item label="服务时间"
                      prop="wantServiceTime">
          <el-date-picker v-model="form.wantServiceTime"
                          type="datetime"
                          class="input-width"
                          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="form.content"
                    :autosize="{ minRows: 2, maxRows: 10 }"
                    :disabled="disabled"
                    type="textarea"
                    clearable
                    class="input-width-textarea"
                    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="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>
        </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')
          ">
          <el-form-item label="实际服务时间"
                        prop="serviceStartTime">
            <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>
          </el-form-item>
          <el-form-item label="完成情况"
                        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-score">
            <el-rate v-model="form.score"
                     :allow-half="true"
                     :disabled="disabled && addType != 'finish'"></el-rate>
          </el-form-item>
          <el-form-item label="备注"
                        prop="finishDesc">
            <el-input v-model="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="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";

export default {
  components: { info, detail },

  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",
        },
      ],
      serviceOptions: [
        {
          label: "志愿者",
          value: "volunteer",
        },
        //  {
        //   label: '社会组织',
        //   value: 'social_org'
        // },
        {
          label: "社区自组织",
          value: "community_org",
        },
        {
          label: "区域党建单位",
          value: "party_unit",
        },
      ],
      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: "categoryName",
          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: "",
      },
      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
    };
  },
  computed: {
    ...mapGetters(["clientHeight", "iframeHeight"]),
    tableHeight () {
      const h = this.clientHeight - this.searchH - 280 + this.iframeHeigh;
      const _h = this.clientHeight - 280 - 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.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;
    },
    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;
    },
    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 == "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 handleLook (row, type) {
      this.detailShow = true
      console.log('row', row)
      this.$nextTick(() => {
        this.$refs.ref_form_detail.initForm(row)
      })
      // await this.formatRowForm(row, type, true);
    },

    detailFormCancle () {

      this.detailShow = false
    },

    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,
      };
      await this.$http
        .post("/heart/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("/heart/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,
      };
      await this.$http
        .post("/heart/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)) {
        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.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("/heart/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.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 getTableData () {
      this.tableLoading = true;
      let params = {
        ...this.searchForm,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
      };
      await this.$http
        .post("/heart/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/buttonstyle.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 {
    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>
