<template>
  <div style="width: 100%;background: #fff;min-height: 700px;"
       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.myconsultation')}}
      </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="tableData"
                stripe
                highlight-current-row
                @row-click="toLook"
                
                class="projectName"
                style="width: 100%">
        <template slot="empty">
          {{$t('common.UserNoData')}}
        </template>
        <el-table-column type="index" fixed :label="$t('common.serialNumber')" width="120"> </el-table-column>
        <el-table-column prop="columnCodeName"  :label="$t('common.projectName')" width='320'> </el-table-column>
        <el-table-column prop="content" :label="$t('common.ConsultingContent')" width='320'> </el-table-column>
        <el-table-column prop="consultMessageInfo.content" :label="$t('common.ReplyContent')" width='320'> </el-table-column>
        <el-table-column :prop="senderDate" :formatter="dateFormat"  :label="$t('common.ConsultationTime')" width="150"></el-table-column>
        <el-table-column fixed="right" prop="address5" :label="$t('common.Option')" width="210">
        <template slot-scope="scope">
        <el-button
            @click="change(scope.row)"
            @click.stop
            v-if="scope.row.consultMessageInfo"
            type="text"
            size="small"
            >
            {{$t('common.check')}}
        </el-button>
        <el-button
            @click.native.prevent="deleteRow(scope.$index, tableData)"
            @click.stop
            type="text"
            size="small">
            {{$t('common.Delete')}}
            </el-button>
        </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;">
            <el-pagination
                style="margin-top: 50px;height: 80px;"
                background
                layout="prev, pager, next"
                :total=totalCount  @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
            </el-pagination>
        </div>
        <el-dialog
        v-if="row.consultMessageInfo"
        :title="$t('common.IntentionConsultation')"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
           <div style="padding: 0 20px;">
               <div class="consultTitle">
                   <span>{{projectName}}</span>
               </div>
               <div style="border-bottom:1px solid #dfdfdf">
                   <div style="margin-top:24px;">
                       <div style="display:inline-block;background:#0091ff;width:20px;height:20px;color:#fff;line-height:20px;border-radius:50%;text-align:center">Q</div>
                       <span style="color:#0091ff;margin-left:10px">{{$t('common.qustion')}}：</span>
                   </div>
                   <p v-html="row.content"></p>
                   <span style="float:right;margin-bottom:20px">{{$t('common.qustionTime')}}：{{dateFormat(row)}}</span>
                    <div style="clear:both"></div>
               </div>
               <div>
                   <div style="margin-top:24px;">
                       <div style="display:inline-block;background:#6dd400;width:20px;height:20px;color:#fff;line-height:20px;border-radius:50%;text-align:center">A</div>
                       <span style="color:#6dd400;margin-left:10px">{{$t('common.replyMessage')}}</span>
                   </div>
                   <p v-html="row.consultMessageInfo.content"></p>
                   <span style="float:right;margin-bottom:20px">{{$t('common.replyMessageTime')}}：{{dateFormat(row)}}</span>
                    <div style="clear:both"></div>
               </div>
           </div>
        </el-dialog>
    </div>
    <div style="margin: 20px 0 0px 30px;"
         v-if="taberIndex === '6'">
      <el-table :data="thinkTankConsultations"
                stripe
                highlight-current-row
                style="width: 100%">
        <template slot="empty">
          {{$t('common.thinkTankConsultation')}}
        </template>
        <el-table-column type="index" fixed :label="$t('common.serialNumber')" width="120"> </el-table-column>
<!--        <el-table-column prop="name"
                         :label="$t('common.Name')"
                         width='200'></el-table-column>-->
        <el-table-column prop="content"
                         :label="$t('common.content')"
                         width='200'></el-table-column>
        <el-table-column prop="thinkTankType"
                         :label="$t('common.thinkTankType')"
                         width='200'></el-table-column>
        <el-table-column prop="thinkTankConsultation.content"
                         :label="$t('common.rescontent')"
                         width='200'></el-table-column>
        <el-table-column prop="senderDate"
                         :label="$t('common.senderDate')"
                         width='200'></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="commit(scope.row)"
                       type="text"
                       size="small"
                       v-if="scope.row.reserveOne == '0'"
                       :disabled="scope.row.statusDict ==='3'">
              {{$t('common.commit')}}
            </el-button>
            <el-button @click.native.prevent="toDelThink(scope.row)"
                       type="text"
                       size="small"
                       :disabled="scope.row.statusDict ==='3'">
              {{$t('common.delete')}}
            </el-button>
            <el-button @click.native.prevent="toReply(scope.row)"
                       type="text"
                       size="small"
                       :disabled="scope.row.statusDict ==='3'">
              {{$t('common.Reply')}}
            </el-button>
            <el-button @click.native.prevent="toLookReply(scope.row)"
                       type="text"
                       size="small"
                       v-if="scope.row.thinkTankConsultation">        
              {{$t('common.view')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;">
        <el-pagination v-if="thinkTankConsultations"
                       style="margin-top: 50px;height: 80px;"
                       background
                       layout="prev, pager, next"
                       :total=totalCount1
                       @size-change="handleSizeChange1"
                       @current-change="handleCurrentChange1"> 
        </el-pagination> 
      </div>
      <el-dialog
        v-if="rowConsultations.thinkTankConsultation"
        :title="$t('common.thinkTankConsultation')"
        :visible.sync="dialogVisible1"
        width="30%"
        :before-close="handleClose">
           <div style="padding: 0 20px;">
               <div style="border-bottom:1px solid #dfdfdf">
                   <div style="margin-top:24px;">
                       <div style="display:inline-block;background:#0091ff;width:20px;height:20px;color:#fff;line-height:20px;border-radius:50%;text-align:center">Q</div>
                       <span style="color:#0091ff;margin-left:10px">{{$t('common.qustion')}}：</span>
                   </div>
                   <p v-html="rowConsultations.content"></p>
                   <span style="float:right;margin-bottom:20px">{{$t('common.qustionTime')}}：{{dateFormat(rowConsultations)}}</span>
                    <div style="clear:both"></div>
               </div>
               <div>
                   <div style="margin-top:24px;">
                       <div style="display:inline-block;background:#6dd400;width:20px;height:20px;color:#fff;line-height:20px;border-radius:50%;text-align:center">A</div>
                       <span style="color:#6dd400;margin-left:10px">{{$t('common.replyMessage')}}</span>
                   </div>
                   <p v-html="rowConsultations.thinkTankConsultation.content"></p>
                   <span style="float:right;margin-bottom:20px">{{$t('common.replyMessageTime')}}：{{dateFormat(rowConsultations)}}</span>
                    <div style="clear:both"></div>
               </div>
           </div>
        </el-dialog>

      <el-dialog
          v-if="thinkTankConsultation"
          :title="$t('common.thinkTankConsultation')"
          :visible.sync="dialogVisible2"
          width="30%"
          :before-close="handleClose">
        <div style="padding: 0 20px;">
          <div style="border-bottom:1px solid #dfdfdf">
            <el-form-item :label="$t('common.Demandforcontent')" prop="content">
              <el-input type="textarea" style="width: 65%;" :autosize="{ minRows: 4, maxRows: 6 }"
                        maxlength="500" show-word-limit
                        :placeholder="$t('common.PleaseEnter') + $t('common.Demandforcontent')"
                        v-model="thinkTankConsultation.content" show-word-limit>
              </el-input>
            </el-form-item>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancelSubmit">{{ $t('common.Cancel') }}</el-button>
              <el-button type="primary" @click="onSubmit">{{ $t('common.Submit') }}</el-button>
            </div>
          </div>
        </div>
      </el-dialog>

    </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 {getReplyAndSenderMessage,gateDelConsultMessageInfo} from "@/api/operation/consultMessageInfo"
import { formatDate } from "@/utils/formatUtils";
import moment from 'moment'
import { getToken,resetToken } from '@/utils/auth'
import {getThinkTankConsultations,commit,deleteTo} from "@/api/thinkTank/thinkTankConsultation";
import Bus from "@/api/bus"; 

export default {
  name: 'userCentermyConcerns',
  extends: Base,
  data () {
    return {
      formInline: {
        user: '',
        region: ''
      },
      taberPhone: [{
        label: "common.IntentionConsultation",
        value: '1'
      }, {
        label: "common.thinkTankConsultation",
        value: '6'
      }],
      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: [],
      tableData: [],
      dialogVisible:false,
      dialogVisible1:false,
      dialogVisible2:false,
      projectName: "",
      totalCount:0,
      totalCount1:0,
      row:{},
      rowConsultations: {},
      param: {
                    pageNo:0,
                    pageSize:10,
                    language:'',
                },
      items: {
        pageNo:0,
        pageSize:10,
      }
    }
  },
  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,THINK_TANK_TYPE_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.thinkTankTypeDicts = result.data[5] || [];
            this.getinitData(this.taberIndex)
          }
        });
      }
    },
    getReply(){

        let token = getToken();
        this.param.language = this.$i18n.locale.toUpperCase();
        getReplyAndSenderMessage(this.param,this.param.language,token).then(res=>{
            console.log(res);
            this.tableData=res.data.consultMessageInfos;
            this.totalCount=res.data.page.totalCount-0;
            this.resetToken();
        })        
    },
    dateFormat(row) {
                return  moment(row.senderDate).format('YYYY-MM-DD');
            },
    getinitData (index) {
      if (index == "1") {
        this.getReply()
      }
      
     
      if (index == "6") {
       this.getThinkTankConsultations();
      }
      
    },
    getThinkTankConsultations(){
       let user = JSON.parse(window.localStorage.getItem('user'));  
      this.items.senderId = user.userId
        getThinkTankConsultations(this.items).then((resulet) => {
        let data = resulet.data;
        if (data.thinkTankConsultations) {
          this.thinkTankConsultations = data.thinkTankConsultations || [];
          this.totalCount1 = data.page.totalCount-0;
          this.thinkTankConsultations.forEach(item => {
            item.senderDate = formatDate(item.senderDate, 'YYYY-MM-DD');
            item.thinkTankType = this.thinkTankTypeDictsMap[item.thinkTankType]
          })
        }
      });
    },
    // 发布
    release (index, rows) {
      console.log(index, rows)
    },
    // 编辑
            change(row) {
                this.row=row;
                this.dialogVisible=true;
                var language = this.$i18n.locale.toUpperCase()
                getBaseProjectInfoName(language,row.columnCode).then(res=>{
                    this.projectName = res.data.baseProjectInfoName;
                })
            },
     // 删除
            deleteRow(index, rows) {
                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(() => {
                    gateDelConsultMessageInfo(rows[index].id).then(res=>{
                        this.$message({
                            message: this.$i18n.locale === 'zh' ? '删除成功!' : 'Successfully deleted',
                            type: 'success'
                        });
                        this.getReply();
                        }).catch((error) => {
                            this.$message.error(res.msg);
                        })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: this.$t('common.Cancelled'),
                    });          
                });
               
            },
    changeToAlliance (index, rows) {
      this.$router.push('userCentermyConcernsProgressCheckAlliance', rows)
    },
    handleCurrentChange(val) {
               
                this.param.pageNo=val;
                this.getReply()
                
            },
    getTaberPhone (item, index) {
      this.taberIndex = item.value
      console.log(this.taberIndex)
    },
    handleCurrentChange1 (val) {
       this.item.pageNo=val;
       this.getThinkTankConsultations();
    },
    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) {
      this.toView('projectPresentationDetails',row.columnCode)
    },
    toView(router, json) {
          window.localStorage.setItem('router', '');
          this.$store.commit('modify', router);
          Bus.$emit("router", router);    //存 Bus.$emit
          const { href } =this.$router.resolve({
            name: router,
            query: {
              key: json,
            }
          });
          window.open(href, '_blank');
        },
    toDel (row) {
      let params = {
        id: row.id
      }
      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(() => {
        deleteByDoor(params).then(result => {
          this.$message({
            type: 'success',
            message: this.$i18n.locale === 'zh' ? '删除成功!' : 'Successfully deleted'
          });
          this.getDicts()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('common.Cancelled'),
        });
      });
    },
    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 Successfully'
          });
          this.getThinkTankConsultations();
        })
      })
        .catch(() => {
        }); 
    },
    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' ? '删除成功!' : 'Successfully Deleted'
          });
          this.getThinkTankConsultations();
        })

      })
        .catch(() => {
        }); 
    },
    toReply(row) {
      this.dialogVisible2=true;
    },
    //取消提交
    cancelSubmit() {
      this.dialogAssueVisible = false;
    },

    toLookReply(row) {
      this.rowConsultations = row;
      this.dialogVisible1=true;
    },
    handleSizeChange(){},
    handleSizeChange1(){}
  }
}
</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;
}

.el-table_body{
    color: red;
}
.projectName >>> .el-table__row td:nth-of-type(2){
  color: #0a0000af !important;
}
.projectName >>> .hover-row td:nth-of-type(2){
  color: #0079ef !important;
}
/* .projectName >>> .el-table__row td:nth-of-type(2){
  color: red ;
} */
.projectName >>> .el-table__row td:nth-of-type(2) .cell{
    cursor: pointer;
}

</style>