<template>
  <div v-if="pageLoading" class="resi-container">
    <el-card class="resi-card-table">
      <div class="resi-row-btn">
        <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="demandOptions"
                :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>
            <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="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="serviceType">
              <el-select v-model="searchForm.serviceType" filterable placeholder="请选择" clearable @change="handleServiceChange">
                <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 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 type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
            <el-form-item>
            <el-button @click="resetForm('searchForm')">重置</el-button>
          </el-form-item>
          </div>
          
        </el-form>
      </div>
      <div class="resi-row-btn">
        <el-button type="success" @click="handleAdd('1', 'add')">新增需求</el-button>
      </div>
      
      <el-table
        :data="tableData"
        row-key="categoryId"
        v-loading="tableLoading"
        border
        max-height="800"
        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"
          :width="item.width"
        >
          <template slot-scope="scope">
            <span>{{ handleFilterSpan(scope.row, item) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button
              @click="handleLook(scope.row)"
              type="text"
              size="small"
              class="btn-color-look"
              >查看</el-button
            >
            <el-button
                v-if="scope.row.level == 1"
                @click="handleAdd('2', 'add', scope.row)"
                type="text"
                size="small"
                >指派</el-button>
            <el-button
              v-if="scope.row.level == 1"
              @click="handleAdd('2', 'add', scope.row)"
              type="text"
              size="small"
              >取消</el-button>
            <el-button
              v-if="scope.row.level == 1"
              @click="handleAdd('2', 'add', scope.row)"
              type="text"
              size="small"
              >完成情况</el-button>
            <el-button
                @click="handleEdit(scope.row, 'edit')"
                type="text"
                size="small"
                class="btn-color-edit"
                >编辑</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"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="需求信息"
      :visible.sync="dialogVisible"
      width="40%"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handlerCancle"
    >
      <el-form label-width="120px" :model="form" :rules="rules" ref="ruleForm" class="form-wr">
        <el-form-item label="所属网格" prop="gridId">
          <el-select v-model="form.gridId" filterable placeholder="请选择" class="input-width" clearable @change="handleGridChange">
            <el-option
              v-for="item in optionsEditG"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="需求类型" prop="parentCode">
          <el-cascader
            v-model="searchForm.categoryCode"
            :options="demandOptions"
            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-select v-model="form.reportType" filterable class="input-width" placeholder="请选择" clearable>
            <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" placeholder="请输入" class="input-width" clearable></el-input>
        </el-form-item>
        <el-form-item label="上报人手机号" prop="reportUserMobile">
          <el-input v-model="form.reportUserMobile" placeholder="请输入" class="input-width" clearable></el-input>
        </el-form-item>
        <el-form-item label="上报时间" prop="reportTime">
          <!-- <el-date-picker
            v-model="form.reportTime"
            type="date"
            class="input-width"
            clearable
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker> -->
          <el-date-picker
            v-model="form.reportTime"
            type="datetime"
            class="input-width"
            clearable
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="需求人" prop="demandUserId">
          <el-select 
            v-model="selectDemandUser" 
            class="input-width" 
            filterable 
            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="date"
            class="input-width"
            clearable
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd">
          </el-date-picker> -->
          <el-date-picker
            v-model="form.wantServiceTime"
            type="datetime"
            class="input-width"
            clearable
            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}" type="textarea" clearable class="input-width-textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div class="resi-btns">
        <el-button size="small" @click="handlerCancle">取消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="btnLoading"
          @click="handleSUbmit"
          >提交</el-button
        >
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      tableLoading: false,
      btnLoading: false,
      disabled: false,
      pageLoading: false,
      dialogVisible: false,
      currentPage: 1,
      pageSize: 20,
      total: null,
      tableData: [],
      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: [],
      demandUserList: [],
      optionsG: [],
      optionsEditG: [],
      tableHeader: [
        {
          label: '状态',
          align: 'center',
          columnName: 'status',
          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: 'reportType',
          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: '120',
          options: []
        }, {
          label: '需求人',
          columnName: 'demandUserName',
          align: 'center',
          width: '80',
          options: []
        }, {
          label: '服务方',
          columnName: 'serviceName',
          align: 'center',
          width: '120',
          options: []
        }, {
          label: '服务时间',
          columnName: 'wantServiceTime',
          align: 'center',
          width: '120',
          options: []
        }
      ],
      customerId: '',
      reportTime: '',
      serviceTime: '',
      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' }],
        parentCode: [{ 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' }]
      }
    }
  },
  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() {
  },
  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]
    },
    resetForm(formName) {
      this.searchForm.reportStartTime = ''
      this.searchForm.reportEndTime = ''
      this.searchForm.wantServiceStartTime = ''
      this.searchForm.wantServiceTime = ''
      this.searchForm.categoryCode = ''
      this.searchForm.level = ''
      this.reportTime = ''
      this.serviceTime = ''
      this.$refs[formName].resetFields()
    },
    handleCateCHange(val) {
      console.log('val', val)
      this.searchForm.categoryCode = val[1] || val[0]
      this.searchForm.level = val.length
    },
    handleCateSlect(val) {
      this.form.parentCode = val[0]
      this.form.categoryCode = val[1]
    },
    handleDemandChange(val) {
      console.log('val', val)
      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 (this.reportTime.length > 0) {
        this.searchForm.reportStartTime = this.reportTime[0]
        this.searchForm.reportEndTime = this.reportTime[1]
      }
      if (this.serviceTime.length > 0) {
        this.searchForm.wantServiceStartTime = this.serviceTime[0]
        this.searchForm.wantServiceTime = this.serviceTime[1]
      }
      this.getTableData()
    },
    handleServiceChange(val) {
      this.getServiceuserList()
    },
    handleGridChange(val) {
      this.getDemandUserList()
    },
    handleAdd(type, addType, row) {
      this.addLevel = type
      this.addType = addType
      if (type == '2') this.form = { ...row, categoryName: '' }
      this.dialogVisible = true
    },
    handlerCancle() {
      this.form.categoryCode = ''
      this.from.parentCode = ''
      this.form.demandUserName = ''
      this.form.demandUserMobile = ''
      this.form.demandUserId = ''
      this.selectDemandUser = ''
      this.$refs.ruleForm.resetFields()
      this.dialogVisible = false
    },
    async handleLook(row) {
      const params = {
        categoryId: row.categoryId,
        usableFlag: !row.usableFlag
      }
      this.$http
        .post('/heart/icresidemanddict/updatestatus', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.getTableData()
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async handleEdit(row, addType) {
      
      this.form = { ...row }
      this.addLevel = row.level
      this.addType = addType
      this.dialogVisible = true
    },
    async addLevelFirst() {
      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.dialogVisible = false
            this.getTableData()
          } 
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
        this.btnLoading = false
    },
    async addLevelChild () {
      const _form = {
        customerId: localStorage.getItem('customerId'),
        categoryName: this.form.categoryName,
        parentCategoryCode: this.form.categoryCode,
        awardPoint: this.form.awardPoint
      }
      await this.$http
        .post('/heart/icresidemanddict/addchild', _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.dialogVisible = false
            this.getTableData()
          } 
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
        this.btnLoading = false
    },
    async editCate() {
      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.dialogVisible = false
            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.addLevelFirst()
          else this.editCate()
          
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      
    },
    handleDel(row) {
      let params = {
        formCode: 'resi_base_info',
        icResiUserId: row.icResiUserId
      }
      console.log('row1', row)
      this.$http
        .post('/epmetuser/icresiuser/delete', 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
    },
    async getGridList(type) {
      const { user } = await this.$store.state
      console.log('user---ppp', user)
      // addorupdate  query
      this.$http
        .post('/gov/org/customergrid/gridoption', { 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
      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.demandOptions = this.getTreeData(res.data)
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    getServiceuserList() {
      if (!this.searchForm.serviceType) return this.$message.error('服务方不能为空')
      const params = {
        serviceName: '',
        serviceType: this.searchForm.serviceType,
        queryPurpose: ''
      }
      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
          }
        })
        .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
          }
        })
        .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>
.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-left: 10px;
    color: rgba(213, 16, 16, 1);
  }
  ::v-deep .btn-color-edit {
    color: rgba(0, 167, 169, 1);
  }
}
.form-wr {
  .input-width {
    width: 260px;

  }
  .input-width-textarea {
    width: 400px;
  }
}

</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>
