<template>
  <div class="div_main">
    <div>
      <div class="div_search">
        <el-form :inline="true"
                 :model="formData"
                 ref="ref_searchform"
                 :label-width="'80px'">
          <div>

            <el-form-item label="服务分类"
                          prop="serviceCategoryId">
              <el-select v-model="formData.serviceCategoryId"
                         placeholder="请选择"
                         size="small"
                         clearable
                         class="item_width_2">
                <el-option v-for="item in categrayArray"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="服务项目"
                          prop="serviceProjectName">
              <el-input v-model="formData.serviceProjectName"
                        class="item_width_1"
                        size="small"
                        clearable
                        placeholder="请输入">
              </el-input>
            </el-form-item>

            <el-form-item label="服务组织"
                          prop="serviceOrgName">
              <el-input v-model="formData.serviceOrgName"
                        class="item_width_2"
                        size="small"
                        clearable
                        placeholder="请输入">
              </el-input>
            </el-form-item>

            <el-form-item label="服务时间"
                          prop="serviceTimeStart">
              <el-date-picker v-model="formData.serviceTimeStart"
                              :picker-options="startPickerOptions"
                              class="item_width_2"
                              size="small"
                              type="date"
                              value-format="yyyy-MM-dd"
                              value="yyyy-MM-dd"
                              placeholder="开始时间">
              </el-date-picker>
              <span class="data-tag">至</span>
              <el-date-picker v-model="formData.serviceTimeEnd"
                              :picker-options="endPickerOptions"
                              class="item_width_2 data-tag"
                              size="small"
                              type="date"
                              value-format="yyyy-MM-dd"
                              value="yyyy-MM-dd"
                              placeholder="结束时间">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="服务状态"
                          prop="serviceStatus">
              <el-select class="item_width_2"
                         v-model="formData.serviceStatus"
                         placeholder="全部"
                         size="small"
                         clearable>
                <el-option v-for="item in statusArray"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>

            </el-form-item>
            <el-form-item label="满意度"
                          prop="satisfaction">
              <el-select class="item_width_2"
                         v-model="formData.satisfaction"
                         placeholder="全部"
                         size="small"
                         clearable>
                <el-option v-for="item in satisfyArray"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>

            </el-form-item>
            <el-button style="margin-left:30px"
                       size="small"
                       class="diy-button--search"
                       @click="handleSearch">查询</el-button>
            <el-button style="margin-left:10px"
                       size="small"
                       class="diy-button--reset"
                       @click="resetSearch">重置</el-button>
          </div>
        </el-form>
      </div>

      <div class="div_table">

        <div class="div_btn">
          <el-button class="diy-button--add"
                     size="small"
                     @click="handleAdd">发起服务</el-button>

          <!-- <el-button @click="handleExport"
                     class="diy-button--reset"
                     size="small">导出</el-button> -->
        </div>

        <el-table :data="tableData"
                  border
                  :header-cell-style="{background:'#2195FE',color:'#FFFFFF'}"
                  class="table"
                  style="width: 100%"
                  :height="maxTableHeight">
          <el-table-column label="序号"
                           fixed="left"
                           type="index"
                           align="center"
                           width="50" />

          <el-table-column prop="serviceCategoryName"
                           align="center"
                           label="服务类别"
                           :show-overflow-tooltip="true">
          </el-table-column>

          <el-table-column prop="serviceProjectName"
                           label="服务项目"
                           align="center"
                           :show-overflow-tooltip="true">
          </el-table-column>

          <el-table-column prop="serviceTimeStart"
                           align="center"
                           width="110"
                           label="服务组织名称"
                           :show-overflow-tooltip="true">

          </el-table-column>

          <el-table-column prop="address"
                           align="center"
                           min-width="210"
                           :show-overflow-tooltip="true"
                           label="服务时间">
            <template slot-scope="scope">
              <span>{{scope.row.serviceTimeStart}}-{{scope.row.serviceTimeEnd}}</span>
            </template>
          </el-table-column>

          <el-table-column prop="serviceStatus"
                           align="center"
                           width="100"
                           label="服务状态"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{scope.row.serviceStatus==='in_service'?'服务':'已完成'}}</span>
            </template>
          </el-table-column>

          <el-table-column prop="servicePeopleNumber"
                           align="center"
                           width="110"
                           label="服务人数"
                           :show-overflow-tooltip="true">
          </el-table-column>

          <el-table-column fixed="right"
                           label="操作"
                           align="center"
                           width="100">
            <template slot-scope="scope">
              <el-button @click="handleDetail(scope.row)"
                         type="text"
                         size="small"
                         class=".div-table-button--detail">详情</el-button>
              <el-button v-if="scope.row.serviceStatus==='in_service'"
                         @click="handleEdit(scope.row)"
                         type="text"
                         size="small"
                         class="div-table-button--edit">编辑</el-button>
              <el-button v-if="scope.row.serviceStatus==='in_service'"
                         @click="handleFreeBack(scope.row)"
                         type="text"
                         size="small"
                         class="div-table-button--edit">反馈</el-button>
              <el-button v-if="scope.row.serviceStatus==='in_service'"
                         @click="handleCancel(scope.row)"
                         type="text"
                         size="small"
                         class="div-table-button--delete">取消</el-button>

            </template>
          </el-table-column>
        </el-table>

        <div>
          <el-pagination @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page.sync="pageNo"
                         :page-sizes="[20, 50, 100, 200]"
                         :page-size="parseInt(pageSize)"
                         layout="sizes, prev, pager, next, total"
                         :total="total">
          </el-pagination>
        </div>

      </div>

    </div>
    <el-dialog v-if="showAdd"
               :visible.sync="showAdd"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'新增记录'"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="showAdd = false">
      <add-form ref="ref_add_form"
                :formType="formType"
                :categrayArray="categrayArray"
                :statusArray="statusArray"
                :satisfyArray="satisfyArray"
                @handleOk="handleOk"
                @handleClose="handleClose"></add-form>
    </el-dialog>
    <el-dialog :visible.sync="showDetail"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'记录详情'"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="showDetail = false">
      <detail-form ref="ref_detail_form"
                   :serviceRecordId="serviceRecordId">
      </detail-form>
    </el-dialog>

  </div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import { mapGetters } from "vuex";
// import eventInfo from "./cpts/event-info";
import axios from "axios";
import addForm from "./addForm";
import detailForm from "./detailForm";
import feedBackForm from "./addForm";

export default {
  components: { addForm, detailForm, feedBackForm },

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

    }
    let startDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      return time.getTime() > nowData
    }

    return {

      user: {},
      agencyId: '',

      tableData: [],
      categrayArray: [],
      statusArray: [
        {
          value: "in_service",
          label: "进行中",
        },
        {
          value: "completed",
          label: "已完成",
        },
      ],
      satisfyArray: [
        {
          value: "bad",
          label: "不满意",
        },
        {
          value: "good",
          label: "基本满意",
        },
        {
          value: "perfect",
          label: "非常满意",
        },

      ],

      formData: {
        serviceCategoryId: '',//服务类别id	
        serviceProjectName: '',//项目名称	
        serviceOrgName: '',//服务组织名称	
        serviceTimeStart: '',//服务开始时间yyyy-MM-dd	
        serviceTimeEnd: '',//服务结束时间yyyy-MM-dd	
        serviceStatus: '',//服务状态。in_service服务中；completed:已完成	
        satisfaction: '',//满意度.不满意:bad、基本满意:good、非常满意:perfect	

      },
      pageNo: 1,
      pageSize: window.localStorage.getItem("pageSize") || 20,
      total: 1,
      endPickerOptions: {
        disabledDate: endDisabledDate
      },
      startPickerOptions: {
        disabledDate: startDisabledDate
      },
      serviceRecordId: '',

      showAdd: false,
      showDetail: false,
      showFeedback: false,
      formType: 'add'

    };
  },
  computed: {
    maxTableHeight () {
      return this.$store.state.inIframe
        ? this.clientHeight - 410 + this.iframeHeigh
        : this.clientHeight - 410;
    },
    ...mapGetters(["clientHeight", "iframeHeight"]),
  },
  watch: {
    // "formData.serviceTimeEnd": function (val) {
    //   if (val && val != '') {
    //     let arrayTemp = val.split(' ')
    //     this.formData.serviceTimeEnd = arrayTemp[0] 
    //   }

    // },
  },
  mounted () {
    console.log(this.$store.state)
    this.user = this.$store.state.user
    this.agencyId = this.user.agencyId
    this.getCategrayList()
    this.getTableData();
  },
  methods: {

    handleSearch (val) {
      console.log(this.formData);
      this.pageNo = 1;
      this.getTableData();
    },
    // 字典
    async getCategrayList () {
      const url = "/sys/dict/data/dictlist"

      let params = {
        dictType: 'ic_service_type'
      }

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

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


    async handleAdd () {
      this.formType = 'add'
      this.showAdd = true;
    },

    async handleDetail (row) {
      this.serviceRecordId = row.serviceRecordId
      this.formType = 'detail'
      // this.showDetail = true
      this.showAdd = true;
    },

    //加载组织数据
    async handleDispose (row) {
      this.serviceRecordId = row.serviceRecordId
      const url = "/gov/project/icEvent/detail";
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/project/icEvent/detail";

      const { data, code, msg } = await requestPost(url, {
        serviceRecordId: this.serviceRecordId,
      });

      if (code === 0) {

        this.eventDetailData = { ...data };

      } else {
        this.$message.error(msg);
      }
    },


    handleClose () {
      this.serviceRecordId = ""
      this.formType = ''

      this.showAdd = false;
      this.getTableData()

    },
    handleOk () {
      this.handleClose()
      this.pageNo = 1

    },

    handleEditSuccess () {
      this.handleClose();
      this.getTableData();
    },

    async handleDel (rowData, rowIndex) {
      console.log(rowData, rowIndex);
      const url =
        "/heart/iccommunityselforganization/delcommunityselforganization";
      const { tableData } = this;

      const { data, code, msg } = await requestPost(url, {
        orgId: tableData[rowIndex].orgId,
      });

      if (code === 0) {
        this.$message.success("删除成功！");
        this.getTableData();
      } else {
        this.$message.error("操作失败！");
      }
    },

    async getTableData () {
      // const url = "/heart/icServiceProject/service/recordList";
      const url = "http://yapi.elinkservice.cn/mock/245/heart/icServiceProject/service/recordList";
      const { pageSize, pageNo, formData } = this;
      const { data, code, msg } = await requestPost(url, {
        pageSize,
        pageNo,
        ...formData,
      });
      if (code === 0) {

        this.total = data.total || 0;
        this.tableData = data.list
          ? data.list.map((item) => {
            return item;
          })
          : [];

        this.tableData.forEach(item => {
          if (item.operationType === '2') {
            item.operationTypeShow = '已转需求'
          }
          if (item.operationType === '1') {
            item.operationTypeShow = '已立项'
          }
          if (item.operationType === '0') {
            item.operationTypeShow = '已回复'
          }

        });
      } else {
        this.$message.error(msg);
      }
    },

    async handleExport () {
      const url = "/gov/project/icEvent/export";
      const { pageSize, pageNo, formData } = this;
      axios({
        url: window.SITE_CONFIG["apiURL"] + url,
        method: "post",
        data: {
          pageSize,
          pageNo,
          ...formData,
        },
        responseType: "blob",
      })
        .then((res) => {
          let fileName = window.decodeURI(
            res.headers["content-disposition"].split(";")[1].split("=")[1]
          );
          console.log("filename", fileName);
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          var url = window.URL.createObjectURL(blob);
          var aLink = document.createElement("a");
          aLink.style.display = "none";
          aLink.href = url;
          aLink.setAttribute("download", fileName);
          document.body.appendChild(aLink);
          aLink.click();
          document.body.removeChild(aLink); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        })
        .catch((err) => {
          console.log("获取导出情失败", err);
          return this.$message.error("网络错误");
        });
    },

    handleSizeChange (val) {

      this.pageSize = val;
      window.localStorage.setItem("pageSize", val);
      this.getTableData();
    },
    handleCurrentChange (val) {

      this.pageNo = val;
      this.getTableData();
    },

    resetSearch () {
      this.formData = {
        gridId: '',
        serviceCategoryId: '',
        serviceProjectName: '',
        serviceOrgName: '',
        mobile: '',
        serviceTimeStart: '',
        serviceTimeEnd: '',
        serviceStatus: '',
      }


      this.pageNo = 1
      // this.getTableData()
    },
  },
};
</script>

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