<template>
  <div style="width: 100%;background: #fff;min-height: 700px;color: #666;"
       class="userCenterMyProject">
    <div style="height: 60px;line-height: 60px;padding-top: 30px;margin-left: 30px;margin-right: 30px; border-bottom: 1px solid rgba(228, 228, 228, 1);">
      {{$t('common.MyApplication')}}
    </div>
    <div style="margin: 20px 0 0px 30px;"
         v-if="$i18n.locale=='zh'">
      <span v-for="(item,index) in taberPhone"
            style="margin-right: 70px;padding: 10px;"
            :class="item.value==taberIndex?'taberPhone1 cursor':'taberPhone2 cursor'"
            @click="getTaberPhone(item,index)">{{$t(item.label)}}</span>
    </div>
    <div style="margin: 20px 0 0px 30px;"
         v-else>
      <span v-for="(item,index) in taberPhone"
            style="margin-right: 40px;padding: 10px;"
            :class="item.value==taberIndex?'taberPhone1 cursor':'taberPhone2 cursor'"
            @click="getTaberPhone(item,index)"
            :style="{marginRight:index==4?'0':'40px'}">{{$t(item.label)}}</span>
    </div>
    <div style="margin: 20px 0 0px 30px;"
         v-if="taberIndex === '1'">
      <el-table :data="baseMemberApplies"
                stripe
                highlight-current-row
                style="width: 100%">
        <template slot="empty">
          {{$t('common.UserNoData')}}
        </template>
        <el-table-column prop="unitZhName"
                         :label="$t('common.Name')"
                         width='200'></el-table-column>
        <el-table-column prop="phaseDict"
                         :label="$t('common.ApplicationStage')"
                         width="150"></el-table-column>
        <el-table-column prop="memberApplyDate"
                         :label="$t('common.ApplicationTime')"
                         width="140"></el-table-column>
        <el-table-column prop="auditStatusDict"
                         :label="$t('common.ReviewState')"
                         width="180"></el-table-column>
        <el-table-column fixed="right"
                         prop="address5"
                         :label="$t('common.Option')"
                         width="210">
          <template slot-scope="scope">
            <el-button @click.native.prevent="change(scope.$index, baseMemberApplies)"
                       type="text"
                       size="small">
              {{$t('common.CheckSchedule')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;">
        <el-pagination v-if="baseMemberApplies"
                       style="margin-top: 50px;height: 80px;"
                       background
                       layout="prev, pager, next"
                       :total="0"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </div>
    <div style="margin: 20px 0 0px 30px;"
         v-if="taberIndex === '2'">
      <el-table :data="baseLeagueApplies"
                stripe
                highlight-current-row
                style="width: 100%">
        <template slot="empty">
          {{$t('common.UserNoData')}}
        </template>
        <el-table-column prop="unitZhName"
                         :label="$t('common.Name')"
                         width='200'></el-table-column>
        <el-table-column prop="phaseDict"
                         :label="$t('common.ApplicationStage')"
                         width="150"></el-table-column>
        <el-table-column prop="leagueApplyDate"
                         :label="$t('common.ApplicationTime')"
                         width="140"></el-table-column>
        <el-table-column prop="auditStatusDict"
                         :label="$t('common.ReviewState')"
                         width="180"></el-table-column>
        <el-table-column fixed="right"
                         prop="address5"
                         :label="$t('common.Option')"
                         width="210">
          <template slot-scope="scope">
            <el-button @click.native.prevent="changeToAlliance(scope.$index, baseLeagueApplies)"
                       type="text"
                       size="small">
              {{$t('common.CheckSchedule')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;">
        <el-pagination v-if="baseLeagueApplies"
                       style="margin-top: 50px;height: 80px;"
                       background
                       layout="prev, pager, next"
                       :total="0"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </div>
    <div style="margin: 20px 0 0px 30px;"
         v-if="taberIndex === '3'">
      <el-table :data="coopCustomServices"
                stripe
                highlight-current-row
                style="width: 100%">
        <template slot="empty">
          {{$t('common.UserNoData')}}
        </template>
        <el-table-column :prop="$i18n.locale=='zh'?'unitZhName':'unitEnName'"
                         :label="$t('common.Name')"
                         width='200'></el-table-column>
        <el-table-column prop="serviceType"
                         :label="$t('common.CustomizedServiceType')"
                         width="150"></el-table-column>
        <el-table-column prop="applyDate"
                         :label="$t('common.ApplicationTime')"
                         width="200"></el-table-column>
        <el-table-column prop="status"
                         :label="$t('common.ReviewState')"
                         width="80"></el-table-column>
        <el-table-column fixed="right"
                         prop="address5"
                         :label="$t('common.Option')"
                         width="210">
          <template slot-scope="scope">
            <el-button @click.native.prevent="edit(scope.row)"
                       type="text"
                       size="small"
                       :disabled="scope.row.statusDict ==='3'">
              {{$t('common.edit')}}
            </el-button>
            <el-button @click.native.prevent="del(scope.row,3)"
                       type="text"
                       size="small"
                       :disabled="scope.row.statusDict ==='3'">
              {{$t('common.delete')}}
            </el-button>
            <el-button @click.native.prevent="view(scope.row)"
                       type="text"
                       size="small">
              {{$t('common.view')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;">
        <el-pagination v-if="coopCustomServices"
                       style="margin-top: 50px;height: 80px;"
                       background
                       layout="prev, pager, next"
                       :total="0"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </div>
    <div style="margin: 20px 0 0 30px;"
         v-if="taberIndex === '4'">
      <el-table :data="coopCustomServices"
                stripe
                highlight-current-row
                style="width: 100%">
        <template slot="empty">
          {{$t('common.UserNoData')}}
        </template>
        <el-table-column :prop="$i18n.locale=='zh'?'unitZhName':'unitEnName'"
                         :label="$t('common.Name')"
                         width='200'></el-table-column>
        <el-table-column prop="serviceType"
                         :label="$t('common.CustomizedServiceType')"
                         width="150"></el-table-column>
        <el-table-column prop="applyDate"
                         :label="$t('common.ApplicationTime')"
                         width="200"></el-table-column>
        <el-table-column prop="status"
                         :label="$t('common.ReviewState')"
                         width="80"></el-table-column>
        <el-table-column fixed="right"
                         prop="address5"
                         :label="$t('common.Option')"
                         width="210">
          <template slot-scope="scope">
            <el-button @click.native.prevent="edit(scope.row)"
                       type="text"
                       size="small"
                       :disabled="scope.row.statusDict ==='3'">
              {{$t('common.edit')}}
            </el-button>
            <el-button @click.native.prevent="del(scope.row,4)"
                       type="text"
                       size="small"
                       :disabled="scope.row.statusDict ==='3'">
              {{$t('common.delete')}}
            </el-button>
            <el-button @click.native.prevent="view(scope.row)"
                       type="text"
                       size="small">
              {{$t('common.view')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;">
        <el-pagination v-if="coopCustomServices"
                       style="margin-top: 50px;height: 80px;"
                       background
                       layout="prev, pager, next"
                       :total="0"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </div>
    <div style="margin: 20px 0 0px 30px;"
         v-if="taberIndex === '5'">
      <el-table :data="resourceApplications"
                stripe
                highlight-current-row
                style="width: 100%">
        <template slot="empty">
          {{$t('common.resourceApplication')}}
        </template>
        <el-table-column prop="reserveOne"
                         :label="$t('common.Name')"
                         width='200'></el-table-column>
        <el-table-column prop="reserveThree"
                         :label="$t('common.CustomizedServiceType')"
                         width="150"></el-table-column>
        <el-table-column prop="createDate"
                         :label="$t('common.ApplicationTime')"
                         width="200"></el-table-column>
        <el-table-column prop="status"
                         :label="$t('common.ReviewState')"
                         width="80"></el-table-column>
        <el-table-column fixed="right"
                         prop="address5"
                         :label="$t('common.Option')"
                         width="210">
          <template slot-scope="scope">
            <el-button @click.native.prevent="toApply(scope.row)"
                       type="text"
                       size="small"
                       :disabled="scope.row.statusDict ==='3'">
              {{$t('common.edit')}}
            </el-button>
            <el-button @click.native.prevent="toDel(scope.row)"
                       type="text"
                       size="small"
                       :disabled="scope.row.statusDict ==='3'">
              {{$t('common.delete')}}
            </el-button>
            <el-button @click.native.prevent="toLook(scope.row)"
                       type="text"
                       size="small">
              {{$t('common.view')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;">
        <el-pagination v-if="coopCustomServices"
                       style="margin-top: 50px;height: 80px;"
                       background
                       layout="prev, pager, next"
                       :total="0"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange">
        </el-pagination>
      </div>

    </div>
  </div>
</template>
<script>
import Base from "@/views/base/Base"
import { getDicts } from '@/api/dict';
import { getBaseMemberApplys } from '@/api/baseMemberApply'
import { getCoopCustomServices, del } from "@/api/cooperation/coopCustomService";
import { getBaseLeagueApplys } from '@/api/cooperation/baseLeagueApply'
import { getBaseResearchApplications, deleteByDoor } from "@/api/research/resource/baseResearchApplication";
import { formatDate } from "@/utils/formatUtils";
import {getThinkTankConsultations,commit,deleteTo} from "@/api/thinkTank/thinkTankConsultation";

export default {
  name: 'userCentermyConcerns',
  extends: Base,
  data () {
    return {
      formInline: {
        user: '',
        region: ''
      },
      taberPhone: [{
        label: "common.MemberApply",
        value: '1'
      }, {
        label: "common.AllianceApply",
        value: '2'
      }, {
        label: "common.CustomServiceApply",
        value: '3'
      }, {
        label: "common.Donation",
        value: '4'
      }, {
        label: "common.resourceApplication",
        value: '5'
      }],
      taberIndex: '',
      baseMemberApplies: [],
      coopCustomServices: [],
      resourceApplications: [],
      memberApplyStatus: [],
      serviceTypeDicts: [],
      childTypeDicts: [],
      supportWayDicts: [],
      phaseDicts: [],
      statusDicts: [],
      phaseDictsEnMap: {
        '1': 'Fill in the information',
        '2': 'Preliminary review',
        '3': 'Approval by the Chairman Office Meeting',
        '4': 'Qualification',
        '5': 'Membership confirmation',
        '6': 'Issue the certificate',
        '7': 'Complete'
      },
      memberApplyStatusEnMap: {
        '1': 'Not audit',
        '2': 'To audit',
        '3': 'Approved',
        '4': 'Rejected',
      },
      customServiceMap: {
        '0': 'Draft',
        '1': 'To audit',
        '2': 'Rejected',
        '3': 'Approved'
      },
      auditStatusDicts: [],
      auditStatusDictsENMap: {
        '1': 'Have not been submitted',
        '2': 'To audit',
        '3': 'First approval rejected',
        '4': 'First approval agreed',
        '5': 'Second approval is rejected',
        '6': 'Second approval is agreed',
      },
      baseLeagueApplies: [],
      releaseStatus: [],
      thinkTankConsultations: [],
      thinkTankTypeDicts: []
    }
  },
  watch: {
    '$i18n.locale' () {
      this.getDicts()
    },
    'taberIndex' () {
      this.getinitData(this.taberIndex);
    }

  },
  mounted () {
    this.taberIndex = this.$route.params.index ? this.$route.params.index : '1'
    this.getDicts()
  },
  computed: {
    releaseStatusMap: function () {
      return this.releaseStatus.array2Obj("value", "label");
    },
    memberApplyStatusMap: function () {
      return this.memberApplyStatus.array2Obj("value", "label");
    },
    phaseDictsMap: function () {
      return this.phaseDicts.array2Obj("value", "label");
    },
    serviceTypeDictsMap: function () {
      return this.serviceTypeDicts.array2Obj("value", "label");
    },
    childTypeDictsMap: function () {
      return this.childTypeDicts.array2Obj("value", "label");
    },
    statusDictsMap: function () {
      return this.statusDicts.array2Obj("value", "label");
    },
    supportWayDictsMap: function () {
      return this.supportWayDicts.array2Obj("value", "label");
    },
    auditStatusDictsMap: function () {
      return this.auditStatusDicts.array2Obj("value", "label");
    },
    thinkTankTypeDictsMap: function () {
      return this.thinkTankTypeDicts.array2Obj("value", "label");
    },
  },
  methods: {
    getDicts () {
      if (this.$i18n.locale === 'zh') {
        getDicts("APPROVE_STATUS_DICT,MEMBER_APPLY_PHASE_DICT,SERVICE_TYPE_DICT,SERVICE_CHILD_TYPE_DICT,SUPPORT_WAY_DICT,CUSTOM_SERVICE_STATUS,MEMBER_APPLY_AUDIT_STATUS_DICT,RELEASE_STATUS_DICT,THINK_TANK_TYPE_DICT").then(result => {
          if (result.data) {
            this.memberApplyStatus = result.data[0];
            this.phaseDicts = result.data[1];
            this.serviceTypeDicts = result.data[2];
            this.childTypeDicts = result.data[3];
            this.supportWayDicts = result.data[4]
            this.statusDicts = result.data[5] || []
            this.auditStatusDicts = result.data[6] || []
            this.releaseStatus = result.data[7] || []
            this.thinkTankTypeDicts = result.data[8] || []
            this.statusDicts.forEach((item, index) => {
              if (index === 1) {
                item.label = '待审核'
              } else if (index === 0) {
                item.label = '待审核'
              }
            });
            this.getinitData(this.taberIndex)
          }
        });
      } else {
        getDicts("APPROVE_STATUS_DICT_EN,MEMBER_APPLY_PHASE_DICT,SERVICE_TYPE_DICT_EN,SERVICE_CHILD_TYPE_DICT_EN,SUPPORT_WAY_DICT_EN").then(result => {
          if (result.data) {
            this.memberApplyStatus = result.data[0];
            this.phaseDicts = result.data[1];
            this.serviceTypeDicts = result.data[2];
            this.childTypeDicts = result.data[3];
            this.supportWayDicts = result.data[4]
            this.getinitData(this.taberIndex)
          }
        });
      }
    },
    getinitData (index) {
      if (index == "1") {
        getBaseMemberApplys().then(res => {
          var data = res.data;
          if (data) {
            this.baseMemberApplies = data.baseMemberApplies || [];
            this.baseMemberApplies.forEach(element => {
              element.memberApplyDate = this.YymmddFormat(new Date(element.memberApplyDate));
              element.auditStatusDict = this.$i18n.locale == 'zh' ? this.auditStatusDictsMap[element.auditStatusDict] : this.auditStatusDictsENMap[element.auditStatusDict];
              element.phaseDict = this.$i18n.locale == 'zh' ? this.phaseDictsMap[element.phaseDict] : this.phaseDictsEnMap[element.phaseDict];
            })
          }
        });
      }

      getBaseLeagueApplys().then(res => {
        var data = res.data;
        if (data) {
          this.baseLeagueApplies = data.baseLeagueApplyList || [];
          this.baseLeagueApplies.forEach(element => {
            element.leagueApplyDate = this.YymmddFormat(new Date(element.leagueApplyDate));
            element.auditStatusDict = this.$i18n.locale == 'zh' ? this.auditStatusDictsMap[element.auditStatusDict] : this.auditStatusDictsENMap[element.auditStatusDict];
            element.phaseDict = this.$i18n.locale == 'zh' ? this.phaseDictsMap[element.phaseDict] : this.phaseDictsEnMap[element.phaseDict];
          })
        }
      });
      let user = JSON.parse(window.localStorage.getItem('user'));
      let param = {
        createBy: user.userId,
        serviceTypeDict: index === '3' ? '1' : index === '4' ? '2' : '1',
      };
      getCoopCustomServices(param).then((res) => {
        const data = res.data;
        if (data.coopCustomServices) {
          this.coopCustomServices = data.coopCustomServices
          this.coopCustomServices.forEach(item => {
            if(item.unitZhName !==''&& item.unitId===''){
              item.unitEnName = item.unitZhName
            }
            if(item.unitEnName !==''&& item.unitId===''){
              item.unitZhName = item.unitEnName
            }
            item.applyDate = formatDate(item.applyDate, 'YYYY-MM-DD HH:mm:ss');
            if (item.serviceTypeDict === '1') {
              item.serviceType = this.serviceTypeDictsMap[item.serviceTypeDict] + '-' + this.childTypeDictsMap[item.childTypeDict];
            } else {
              item.serviceType = this.serviceTypeDictsMap[item.serviceTypeDict] + '-' + this.supportWayDictsMap[item.supportWayDict]
            }
            item.status = this.$i18n.locale === 'zh' ? this.statusDictsMap[item.statusDict] : this.customServiceMap[item.statusDict]
          })
        }else {
          this.coopCustomServices = [];
        }
      })
      let params = {
        createBy: user.userId,
      };
      getBaseResearchApplications(params).then((resulet) => {
        let data = resulet.data;
        if (data.baseResearchApplications) {
          this.resourceApplications = data.baseResearchApplications || [];
          this.resourceApplications.forEach(item => {
            item.reserveThree = this.$i18n.locale === 'zh' ? "调研资源" : "Research Resource";
            item.createDate = formatDate(item.createDate, 'YYYY-MM-DD HH:mm:ss');
            item.status = this.$i18n.locale === 'zh' ? this.releaseStatusMap[item.status] : this.releaseStatusMap[item.status]
          })
        }
      });
      let items = {
        senderId: user.userId,
      };

      getThinkTankConsultations(items).then((resulet) => {

        let data = resulet.data;
        if (data.thinkTankConsultations) {
          this.thinkTankConsultations = data.thinkTankConsultations || [];
          this.thinkTankConsultations.forEach(item => {
            item.senderDate = formatDate(item.senderDate, 'YYYY-MM-DD HH:mm:ss');
            item.thinkTankType = this.thinkTankTypeDictsMap[item.thinkTankType]
          })
        }
      });
    },
    // 发布
    release (index, rows) {
      console.log(index, rows)
    },
    // 编辑
    change (index, rows) {
      this.$router.push('myConcernsProgressCheck', rows)
    },
    changeToAlliance (index, rows) {
      this.$router.push('userCentermyConcernsProgressCheckAlliance', rows)
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
    },
    getTaberPhone (item, index) {
      this.taberIndex = item.value
      console.log(this.taberIndex)
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
    },
    YymmddFormat (newDate) {
      let Month = newDate.getMonth() + 1;
      Month = Month >= 10 ? Month : '0' + Month;
      let d = newDate.getDate();
      d = d >= 10 ? d : '0' + d
      return [
        [newDate.getFullYear(), Month, d].join('-'), [newDate.getHours(), newDate.getMinutes()].join(':')
      ].join(' ');
    },
    edit (row) {
      console.log(row);
      this.$router.push({ name: 'IntroductionMemberProfile', query: { data: row, key: 'custom', index: this.taberIndex } })
    },
    toApply (row) {
      console.log(row);
      this.$router.push({ name: 'resourceSharingResourceApply', query: { key: row.id } })
    },
    toLook (row) {
      console.log(row);
      this.$router.push({ name: 'resourceSharingResourceApply', query: { key: row.id, value: false } })
    },
    toDel (row) {
      let params = {
        id: row.id
      }
      this.$confirm('确定删除该记录吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteByDoor(params).then(result => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getDicts()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    del (row, index) {
      this.$confirm(this.$i18n.locale === 'zh' ? '确定删除？' : 'Are you sure you want to delete?', this.$t('common.Tips'), {
        confirmButtonText: this.$t('common.OK'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        del(row.id).then(() => {
          this.$message({
            type: 'success',
            message: this.$i18n.locale === 'zh' ? '删除成功!' : 'Successfully deleted'
          });
        })
        this.getinitData(index);
      })
          .catch(() => {
            this.$message({
              type: "info",
              message: this.$t('common.Cancelled'),
            });
          });

    },
    view (row) {
      this.$router.push({ name: 'IntroductionMemberProfile', query: { data: row, key: 'custom', disable: true, index: this.taberIndex } })
    },
    commit(row) {
      this.$confirm(this.$i18n.locale === 'zh' ? '确定提交？' : 'Are you sure you want to commit?', this.$t('common.Tips'), {
        confirmButtonText: this.$t('common.OK'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        commit(row.id).then(() => {
          this.$message({
            type: 'success',
            message: this.$i18n.locale === 'zh' ? '提交成功!' : 'Commit deleted'
          });
        })
        this.getinitData(index);
      })
          .catch(() => {
            this.$message({
              type: "info",
              message: this.$t('common.Cancelled'),
            });
          });
    },
    toDelThink(row) {
      this.$confirm(this.$i18n.locale === 'zh' ? '确定删除？' : 'Are you sure you want to delete?', this.$t('common.Tips'), {
        confirmButtonText: this.$t('common.OK'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        deleteTo(row.id).then(() => {
          this.$message({
            type: 'success',
            message: this.$i18n.locale === 'zh' ? '删除成功!' : 'Delete deleted'
          });
        })
        this.getinitData(index);
      })
          .catch(() => {
            this.$message({
              type: "info",
              message: this.$t('common.Cancelled'),
            });
          });
    },
    toLookReply(row) {},
  }
}
</script>
<style scoped>
.el-input {
  width: 200px;
}

.el-form-item__content,
.el-select {
  width: 200px !important;
}

.el-table thead {
  background: #eee;
}

.userCenterMyProject >>> .el-pagination .el-pager li,
.userCenterMyProject >>> .el-pagination .btn-next,
.userCenterMyProject >>> .el-pagination .btn-prev {
  width: 35px;
  height: 35px;
  line-height: 35px;
}

.userCenterMyProject
>>> .el-pagination.is-background
.el-pager
li:not(.disabled).active {
  background: #0050d8;
}

.taberPhone1 {
  border-bottom: 2px solid #0c5afa;
  color: #0c5afa;
}
</style>