<template>
  <div class="g-main">
    <div>
      <div class="m-search">
        <el-form :inline="true"
                 :model="formData"
                 ref="ref_searchform"
                 :label-width="'100px'">
                 <el-form-item label="服务类别" prop="categoryCode">
                    <el-cascader
                      v-model="formData.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-form-item>

            <el-form-item label="服务时间"
                          prop="serviceTimeStart">
              <el-date-picker v-model="formData.serviceTimeStart"
                              :picker-options="startPickerOptions"
                              class="u-item-width-daterange"
                              size="small"
                              type="date"
                              value-format="yyyy-MM-dd"
                              value="yyyy-MM-dd"
                              placeholder="开始时间">
              </el-date-picker>
              <span class="u-data-tag">至</span>
              <el-date-picker v-model="formData.serviceTimeEnd"
                              :picker-options="endPickerOptions"
                              class="u-item-width-daterange u-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="serviceName">
              <el-input v-model="formData.serviceName"
                        class="u-item-width-normal"
                        size="small"
                        clearable
                        placeholder="请输入">
              </el-input>
            </el-form-item>

            <el-form-item label="服务组织"
                          prop="serviceOrgType">
              <el-select v-model="formData.serviceOrgType"
                         class="u-item-width-daterange"
                         placeholder="请选择"
                         size="small"
                         clearable
                         @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="formData.serviceOrgId"
                         class="u-item-width-daterange u-data-tag"
                         filterable
                         placeholder="请选择"
                         size="small"
                         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="serviceStatus">
              <el-select class="u-item-width-normal"
                         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="u-item-width-normal"
                         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-row type="flex" >
          <el-col :span="24" align="right">
            <el-button style="margin-left:30px"
                       size="small"
                       type="primary "
                       @click="handleSearch">查询</el-button>
            <el-button style="margin-left:10px"
                       is-plain
                       class="diy-button--white el-button--default"
                       size="small"
                       @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
           
        </el-form>
      </div>

      <div class="m-table">
        <div class="div_btn">
          <div class="div_btn_left">
            <el-button 
                     size="small"
                     @click="handleAdd"
                     type="primary"
                     icon="el-icon-plus"
                     style="margin-right:10px"
                     >新增</el-button>
          </div>
          <el-button @click="handleExport"
                      type="primary"
                      size="small"
                      class="diy-button--white el-button--default"
                      >导出</el-button>
              <el-button   type="primary" @click="onDeleteBatch" size="small">
                批量删除
            </el-button>
        </div>

        <el-table :data="tableData"
                  border
                  v-loading="tableLoading"
                  class="m-table-item"
                  style="width: 100%"
                  :height="maxTableHeight"
                  @select-all="onMultiSelect"
                  @selection-change="onMultiSelect">

            <el-table-column
                    type="selection"
                    fixed="left"
                    align="center"
                    width="50"/>
                    
          <el-table-column label="序号"
                           fixed="left"
                           type="index"
                           align="center"
                           width="50" />

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

          <el-table-column prop="serviceName"
                           align="center"
                           min-width="150"
                           label="服务事项"
                           :show-overflow-tooltip="true">

          </el-table-column>
          <el-table-column prop="sourceName"
                           align="center"
                           min-width="150"
                           label="来自"
                           :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="serviceTimeStart"
                           align="center"
                           width="300"
                           :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="serviceOrgName"
                           align="center"
                           min-width="150"
                           label="服务方"
                           :show-overflow-tooltip="true">

          </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="servedPersonQty"
                           align="center"
                           width="110"
                           label="服务人数"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-button @click="handlePersonList(scope.row)" type="text" size="small">
                {{ scope.row.servedPersonQty }}
              </el-button>
            </template>
          </el-table-column>

          <el-table-column fixed="right"
                           label="操作"
                           align="center"
                           width="220">
            <template slot-scope="scope">
              <el-button @click="handleDetail(scope.row)"
                         type="text"
                         size="small"
                        >查看</el-button>
              <el-button 
                         @click="handleEdit(scope.row)"
                         type="text"
                         size="small"
                         >编辑</el-button>
                         <!-- 临时去掉人员名单与反馈 -->
              <el-button v-if="scope.row.serviceStatus==='in_service'"
                         @click="handleFeedback(scope.row)"
                         type="text"
                         size="small"
                         >反馈</el-button>
              <!-- <el-button v-if="scope.row.policyId"
                         @click="handlePersonList(scope.row)"
                         type="text"
                         size="small"
                         >人员名单</el-button> -->
                         
            <!-- 暂时不限制删除按钮，任何状态都允许删除，产品要求的 -->
            <!-- v-if="scope.row.serviceStatus==='in_service'" -->
              <el-button 
                         @click="handleDel(scope.row)"
                         type="text"
                         size="small"
                       >删除</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="addDiaTitle"
               :modal-append-to-body="false"
               width="720px"
               top="5vh"
               class="dialog-h"
               @closed="showAdd = false">
      <add-form ref="ref_add_form"
                :formType="formType"
                :statusArray="statusArray"
                :satisfyArray="satisfyArray"
                :serviceRecordId="serviceRecordId"
                :serviceName="serviceName"
                @handleOk="handleOk"
                @handleClose="handleClose"></add-form>
    </el-dialog>
    <!-- 编辑与新增写在一个组件中 -->
    <!-- <el-dialog v-if="showEdit"
               :visible.sync="showEdit"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'编辑'"
               :modal-append-to-body="false"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="showEdit = false">
      <edit-form ref="ref_edit_form"
                 :serviceRecordId="serviceRecordId"
                 :serviceOrgName="serviceOrgName"
                 :satisfyArray="satisfyArray"
                 :statusArray="statusArray"
                 @handleOk="handleOk"
                 @handleClose="handleClose"
                 :formType="formType">
      </edit-form>
    </el-dialog> -->
    <el-dialog v-if="showDetail"
               :visible.sync="showDetail"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="detailDiaTitle"
               :modal-append-to-body="false"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="diaDetailClose">
      <detail-form ref="ref_detail_form"
                   :serviceRecordId="serviceRecordId"
                   :serviceOrgName="serviceOrgName"
                   :satisfyArray="satisfyArray"
                   :statusArray="statusArray"
                   @diaDetailClose="diaDetailClose">
      </detail-form>
    </el-dialog>
    <el-dialog v-if="showPersonList"
               :visible.sync="showPersonList"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'人员名单'"
               width="1150px"
               top="5vh"
               class="dialog-h"
               @closed="showPersonList = false">
      <person-list ref="ref_person_list"
                   :serviceId="commonServiceId"
                   :tagId="tagId">
      </person-list>
    </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.vue";
import editForm from "./editForm";
import feedBackForm from "./addForm";
import personList from "./personList";
// 其他组件其他页面有调用
export default {
  components: { addForm, detailForm, feedBackForm, editForm, personList },
  

  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 {
      // 公共服务分类
      tableLoading: false,
      user: {},
      agencyId: '',
      searchH:0,
      tableData: [],

      searchdemandOptions:[],

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

      ],

      formData: {
        categoryCode:'',
        parentCategoryCode:'',
        serviceName: '',//项目名称
        serviceOrgType: '',//服务组织类型
        serviceOrgId: '',//服务组织Id
        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: '',
      serviceName: '',
      serviceOrgName: '',

      showAdd: false,
      showEdit: false,
      showDetail: false,
      showFeedback: false,
      formType: 'add',
      addDiaTitle: '指派服务',
      detailDiaTitle: '服务详情',

      serviceOptions: [],
      serviceOptiondList: [],

      commonServiceId: null,
      tagId: null,
      showPersonList: false,
      ruleList: [],

      // 多选行
      multiSelectedRows: []
    };
  },
  computed: {
    maxTableHeight () {
      const h =
      this.clientHeight - this.searchH - 450 + this.iframeHeight;
      const _h = this.clientHeight - 450 - this.searchH;
      return this.$store.state.inIframe ? h : _h;
    },
    ...mapGetters(["clientHeight", "iframeHeight"]),
  },
  watch: {
    // "formData.serviceTimeEnd": function (val) {
    //   if (val && val != '') {
    //     let arrayTemp = val.split(' ')
    //     this.formData.serviceTimeEnd = arrayTemp[0] + ' 23:59:59'
    //   }

    // },
  },
  mounted () {
    console.log(this.$store.state)
    this.user = this.$store.state.user
    this.agencyId = this.user.agencyId
    this.getDictOptions()
    this.getTableData();
    this.getDemandOptions()
  },
  methods: {
    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);
          }
        })
        .catch(() => {
          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;
    },
  
    handleCateCHange(val) {
        this.formData.parentCategoryCode = val[0];
        this.formData.categoryCode = val[1];
    },
    handleSearch (val) {
      console.log(this.formData);
      this.pageNo = 1;
      this.getTableData();
    },
    // 获取服务组织
    async getDictOptions () {
      const url = "/sys/dict/data/dictlist"

      let params = {
        dictType: 'user_demand_service_type'
      }

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

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

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

    async getServiceuserList (serviceType, query) {
      if (!serviceType) return false;

      const params = {
        serviceName: "",
        serviceType: serviceType,
        queryPurpose: query,
      };
      await this.$http
        .post("/governance/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 handlePersonList (row) {
      this.commonServiceId = row.serviceRecordId;
      this.tagId = row.resiSearchTagId;
      this.showPersonList = true;
    },

    async loadRuleList () {

      const url = "/governance/policy/rulelist/" + this.policyId

      let params = {}

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

      if (code === 0) {
        this.ruleList = data

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

    },


    async handleAdd () {
      this.addDiaTitle = '指派服务'
      this.formType = 'add'
      this.showAdd = true;
    },

    async handleDetail (row) {
      this.detailDiaTitle = "服务详情"
      this.serviceRecordId = row.serviceRecordId
      this.serviceOrgName = row.serviceOrgName

      // this.formType = 'detail'
      this.showDetail = true

    },
    diaDetailClose () {
      console.log(this.$refs.ref_detail)
      this.$refs.ref_detail_form.diaDestroy()
      this.showDetail = false
    },
    async handleEdit (row) {
      this.addDiaTitle = "编辑服务"
      this.serviceRecordId = row.serviceRecordId
      this.serviceOrgName = row.serviceOrgName
      this.formType = 'edit'
      this.showAdd = true

    },

    //加载组织数据
    async handleFeedback (row) {

      this.serviceRecordId = row.serviceRecordId
      this.serviceName = row.serviceName
      this.addDiaTitle = '服务反馈'
      this.formType = 'feedback'
      this.showAdd = true;
    },


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

      this.showAdd = false
      this.showDetail = false
      this.showEdit = false


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

    },


    async handleDel (row) {

      this.serviceRecordId = row.serviceRecordId

      this.$confirm("确认删除服务?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.cancelFuwu([row.serviceRecordId])
        })
        .catch(err => {
          if (err == "cancel") {
            // this.$message({
            //   type: "info",
            //   message: "已取消删除"
            // });
          }

        });

    },

    async cancelFuwu (serviceRecordIds) {

      const url = '/governance/icServiceWarmRecord/searchDeleteBatch';

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

      if (code === 0) {
        this.$message.success("取消成功！");
        this.getTableData();
      } else {
        this.$message.error(msg);
      }
    },

    async getTableData () {
      this.tableLoading = true
      const url = "/governance/icServiceWarmRecord/searchList";

      const { pageSize, pageNo, formData } = this;
      const { data, code, msg } = await requestPost(url, {
        pageSize,
        pageNo,
        ...formData,
      });

      this.tableLoading = false
      if (code === 0) {

        this.total = data.total ;
        this.tableData = data.list



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

    async handleExport () {
      //导出改接口-'服务找人'
      const url = "/governance/icServiceWarmRecord/searchExport";
      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.openxmlformats-officedocument.spreadsheetml.sheet" });
          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 = {
        serviceName: '',//项目名称
        serviceOrgType: '',//服务组织类型
        serviceOrgId: '',//服务组织Id
        serviceTimeStart: '',//服务开始时间yyyy-MM-dd
        serviceTimeEnd: '',//服务结束时间yyyy-MM-dd
        serviceStatus: '',//服务状态。in_service服务中；completed:已完成
        satisfaction: '',//满意度.不满意:bad、基本满意:good、非常满意:perfect
      }


      this.pageNo = 1
      this.getTableData()
    },

    // 多选
    onMultiSelect(row) {
        this.multiSelectedRows = row;
    },

    // 批量删除
    onDeleteBatch() {
        if (this.multiSelectedRows.length == 0) {
            return;
        }

        this.$confirm("删除之后无法恢复，确认删除？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(() => {
            let serviceRecordIds = this.multiSelectedRows.map(item => item.serviceRecordId)
            this.cancelFuwu(serviceRecordIds)
        })
        .catch((err) => {
            if (err == "cancel") {
            }
        });
    }
  },

  props: {


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