<template>
  <div>

    <el-dialog
        :before-close="handleClose"
        :modal="true"
        :modal-append-to-body="false"
        :visible.sync="dialogVisible"
        class="dissatisfied-detail"
        title=""
        width="1118px"
    >
      <div class="content">
        <div class="main-title main-title2">
          <Title :text="!isSelect?'共性需求详情':'共性需求派单'"/>
        </div>
        <div class="contents">
          <el-row>
            <el-col :span="12">
              <div class="items">
                <div class="label">需求类别：</div>
                <div class="value">{{ detail.categoryName }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="items">
                <div class="label">需求标题：</div>
                <div class="value">{{ detail.title }}</div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="items">
                <div class="label">详细说明：</div>
                <div class="value">
                  {{ detail.content }}
                </div>
              </div>
            </el-col>
          </el-row>

          <el-row v-if="isSelect">
            <el-col :span="24">
              <div class="items">
                <div class="label">服务方：</div>
                <el-select
                    v-model="form.serverOrgType"
                    class="select"
                    clearable
                    popper-class="selectPopClass"
                    @change="handleServiceChange('add', $event)"
                >
                  <el-option
                      v-for="item in serviceOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
                <el-select v-model="form.serverOrgId" class="select" popper-class="selectPopClass">
                  <el-option
                      v-for="item in serviceOptiondList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  >
                  </el-option>
                </el-select>
                <CallPhone icon="el-icon-phone"/>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="items">
                <div class="label">自动通知服务方：</div>
                <el-checkbox-group
                    v-model="form.noticeApproches"
                    class="select"
                    popper-class="selectPopClass"
                    text-color="#fff"
                >
                  <el-checkbox label="1" value="1">短信通知</el-checkbox>
                  <el-checkbox label="2" value="2">微信公众号消息通知</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="items">
                <div class="label">服务范围：</div>
                <el-cascader
                    :key="iscascaderShow"
                    ref="myCascader"
                    v-model="form.serviceScopeList"
                    :options="casOptions"
                    :props="optionProps"
                    :show-all-levels="false"
                    class="select"
                    collapse-tags
                    popper-class="selectPopClass"
                ></el-cascader>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="items">
                <div class="label">服务时间：</div>
                <el-date-picker
                    v-model="form.date"
                    :append-to-body="false"
                    class="select"
                    end-placeholder="结束日期"
                    format="yyyy-MM-dd"
                    popper-class="date-current-weiyi"
                    range-separator="至"
                    start-placeholder="开始日期"
                    type="daterange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                />
              </div>
            </el-col>
          </el-row>

          <div v-if="!isSelect" class="btn-group">
            <el-button class="green" plain round type="success" @click="handleDispatch">资源调度</el-button>
          </div>

          <div v-else class="btn-group">
            <el-button class="cancel" plain round type="success" @click="handleCancel">取消</el-button>
            <el-button class="sure" plain round type="warning" @click="handleSure">确定</el-button>
          </div>

        </div>
      </div>
    </el-dialog>
    <ResourceScheduling
        ref="ResourceScheduling"
        :currentLevelData="currentLevelData"
        @handle="dispatchOrder"
    />

  </div>
</template>

<script>
import Title from "@/views/dataBoard/satisfactionEval/components/Title";
import ResourceScheduling from "@/views/dataBoard/overview/components/ResourceScheduling.vue";
import CallPhone from "@/views/dataBoard/cpts/CallPhone";
import {requestPost} from "@/js/dai/request";

export default {
  name: "ServiceDetails",
  components: {Title, ResourceScheduling, CallPhone},
  props: {
    currentLevelData: {
      type: Object,
      default: () => {
      },
    }
  },
  data() {
    return {
      dialogVisible: false,
      isSelect: false,
      form: {
        date: [],
        noticeApproches: [],
        serviceScopeList: [], //
        serviceTimeStart: "", //服务起始时间yyyy-MM-dd
        serviceTimeEnd: "", //服务截止时间yyyy-MM-dd
        serverOrgType: "", //服务组织类型 社区自组织：community_org， 志愿者：ic_user_volunteer， 联建单位：party_unit
        serverOrgId: "", //服务组织Id
      },
      detail: {},
      iscascaderShow: 0,
      casOptions: [],
      optionProps: {
        multiple: true,
        value: "objectId",
        label: "objectName",
        children: "children",
        checkStrictly: true,
        emitPath: false,
      },
      serviceOptiondList: [],
      serviceOptions: [],
      sarr: [],
    };
  },
  methods: {
    handleClose(done) {
      this.dialogVisible = false;
      this.detail = {}
      this.handleCancel()
    },
    handleCancel() {
      this.isSelect = false;
      this.form = {}
    },
    open(id) {
      console.log(this.currentLevelData, 'this.currentLevelData2')
      this.dialogVisible = true;
      this.getDetail(id);
    },
    getDetail(id) {
      this.$http.get('/governance/commonDemand/detail/' + id, {}).then(({data: {data}}) => {
        this.detail = data
      });
    },
    handleDispatch() {
      this.$refs.ResourceScheduling.open()
    },
    handleSupervision() {
      this.$refs.supervision.open()
    },
    async getDictOptions() {
      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 handleServiceChange(type, val) {
      this.form.serverOrgId = ''
      await this.getServiceuserList(val);
    },
    async getServiceuserList(serverOrgType) {
      if (!this.detail.commonServiceTypeId || !serverOrgType) return;
      const url = "/actual/base/serviceitem/listServerOrg";
      let params = {
        serviceTypeId: this.detail.commonServiceTypeId,
        serverOrgType: serverOrgType,
        businessType: "common_service",
      };
      let {data, code, msg} = await requestPost(url, params);
      if (code == 0) {
        this.serviceOptiondList = data;
      } else if (code >= 8000) {
        this.$message.error(msg);
      }
    },
// 获取服务范围树
    async loadScopeTree() {
      const url = "/gov/org/icServiceProject/service/serviceScopeTree";
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {};
      const {data, code, msg} = await requestPost(url, params);
      if (code === 0) {
        ++this.iscascaderShow;
        this.casOptions = [];
        this.scopeIdArray = [];
        await this.handleData(data.children);
        this.casOptions.push(data);
      } else {
        this.$message.error(rspMsg);
      }
    },
    //子级为空数组的赋值为null解决有空白页的问题
    handleData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children != null) {
          if (data[i].children.length == 0) {
            data[i].children = null;
          } else if (data[i].children != null) {
            this.handleData(data[i].children);
          }
        }
      }
      return data;
    },
    getLastItem(list, vals, key) {
      let LIST = list || [];
      for (let item of LIST) {
        // console.log(item[key]);
        for (let i of vals) {
          if (item[key] === i) {
            this.sarr.push(item);
          } else if (item["objectType"] == "district") {
            this.getLastItem(item.children, vals, key);
          } else {
            this.getLastItem(item.children, vals, key);
          }
        }
      }
    },
    handleSure() {

      const map = new Map();
      this.getLastItem(
          this.casOptions,
          this.form.serviceScopeList,
          "objectId"
      );
      let serviceScopeListCopy = this.form.serviceScopeList.slice();

      //递归出的数据会有重复,因为一个街道下面有两个社区的话就会循环push两遍,在这里去重
      this.newArr = this.sarr.filter(
          (v) => !map.has(v.objectId) && map.set(v.objectId, 1)
      );
      for (let i in this.newArr) {
        this.form.serviceScopeList.push({
          objectId: this.newArr[i].objectId,
          objectType: this.newArr[i].objectType,
          objectName: this.newArr[i].objectName,
        });
      }
      this.newArr = [];
      //  如果是编辑的话回填的数据会有数组字符串需要将不是对象属性的过滤掉
      let arr = [];
      this.form.serviceScopeList.forEach((item) => {
        if (typeof item != "string") {
          arr.push(item);
        }
      });
      this.form.serviceScopeList = arr;
      
      let params = {
        ...this.detail,
        assignFlag: 1,
        assignInfo: {
          serviceScopeList: this.form.serviceScopeList,
          noticeApproches: this.form.noticeApproches.length > 0? this.form.noticeApproches: 0,
          serviceTimeStart: this.form.date[0],
          serviceTimeEnd: this.form.date[1],
          serverOrgType: this.form.serverOrgType,
          serverOrgId: this.form.serverOrgId,
        }
      }
      this.$http.post('/governance/commonDemand/update', params).then((res) => {
        this.handleClose()
        this.$emit('ok')
      })
    },
    dispatchOrder(data) {
      this.isSelect = true
      this.getDictOptions()
      this.loadScopeTree()
    }
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/scss/dataBoard/dialog.scss";

.contents {
  padding: 40px 50px;

  .items {
    font-size: 14px;
    line-height: 34px;
    position: relative;
    display: flex;
    //align-items: flex-start;
    align-items: center;
    margin-bottom: 17px;

    .label {
      white-space: nowrap;
      color: #9CB4D3;
    }

    .value {
      color: #FFFFFF;
    }
  }
}

.hr {
  height: 1px;
  margin: 25px 0;
  opacity: .4;
  border-bottom: 1px #0E79D6 dashed;
}


.btn-group {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;

  .green {
    color: #00CD96;
    border: 1px solid #00CD96;
    background: rgba(39, 189, 127, 0.3);
  }

  .el-button {
    width: 136px;
    height: 36px;
    margin: 0 20px;
  }

  .orange {
    color: #FD8904;
    border: 1px solid #FD8904;
    background: rgba(253, 137, 4, 0.3);
  }

  .sure {
    color: #8ED3FF;
    border: 1px solid #006CFF;
    background: rgba(0, 108, 255, 0.5);
  }

  .cancel {
    color: #B6D2FF;
    border: 1px solid #6496E8;
    background: rgba(116, 146, 194, 0.6);
  }

}

.select {
  margin-right: 16px;
}

/deep/ .el-date-editor .el-range-separator {
  color: #fff;
}

/deep/ .el-checkbox {
  color: #fff;
}

/deep/ .el-input__inner {
  width: 360px;
  height: 40px;
  color: #fff;
  border: 1px solid #0E3978;
  border-radius: 20px;
  background: rgba(0, 23, 66, 0.72);
}

/deep/ .el-range-editor .el-range-input {
  color: #fff;
  background: none;
}

::v-deep .date-current-weiyi {
  border-color: #006cff;
  background: rgba(3, 19, 51, 0.9);
  box-shadow: inset 0px 0px 16px 0px rgba(0, 145, 255, 1);

  .el-date-picker__header-label {
    color: #ffffff;
  }

  .el-picker-panel__icon-btn {
    color: #ffffff;
  }

  .el-month-table {
    td {
      .cell {
        color: #ffffff;
      }
    }
  }

  .el-month-table td.current:not(.disabled) .cell {
    color: #fff;
    background-color: #409eff;
  }

  .el-month-table td.today:not(.disabled) .cell {
    color: #0056d6;
  }

  .el-date-picker__header--bordered {
    border-bottom: solid 1px #006cff;
  }
}
/deep/ .el-cascader__tags .el-tag {
  background-color: rgba(#409eff, .5) !important;
  color: #fff!important;
}
</style>
