<template>
  <view class="app-container">
    <u-navbar :title="title" safeAreaInsetTop placeholder>
      <view class="flex justify-between" slot="left" @click="loginOut">
        <u-icon size="15" name="/static/images/icon/login-out.png"></u-icon>
        <view class="text-red margin-left-xs">
          退出
        </view>
      </view>
    </u-navbar>
    <view class="flex justify-between align-center padding-sm bg-white">
      <view class="w70">
        <u-search v-model="keyword" bgColor="#fff" borderColor="#EC1E19" :clearabled="true" placeholder="请输入户名"
          :actionStyle="actionStyle" @custom="onSearch" @clear="onClear"></u-search>
      </view>
      <view class="w30 margin-left">
        <u-checkbox-group activeColor="#EC1E19" v-model="approvalValue" placement="column" @change="checkboxChange">
          <u-checkbox v-for="(item, index) in approval" :key="index" :label="item.name" :name="item.name">
          </u-checkbox>
        </u-checkbox-group>
      </view>
    </view>
    <view class="">
      <uv-drop-down ref="dropDown" sign="dropDown_1" :extra-icon="{name:'arrow-down-fill',color:'#666',size:'26rpx'}"
        :extra-active-icon="{name:'arrow-up-fill',color:'#3c9cff',size:'26rpx'}">
        <uv-drop-down-item name="order" type="2" label="财年" value="all">
        </uv-drop-down-item>
        <uv-drop-down-item name="type" type="2" label="项目公司" value="0">
        </uv-drop-down-item>
        <uv-drop-down-item name="type" type="2" label="状态" value="0">
        </uv-drop-down-item>
        <uv-drop-down-item name="type" type="2" label="类型" value="0">
        </uv-drop-down-item>
      </uv-drop-down>
    </view>

    <view class="usuallyCard margin padding" v-if="list.length" v-for="(item,index) in list" :key="index"
      @click="viewDetail(item)">
      <view class="flex flex-direction">
        <view class="flex justify-between">
          <view class="">
            {{item.fiscalYear || "--"}}财年
          </view>
          <view class="flex">
            <u-tag class="margin-right" :bgColor="bfColorStatus(item.ticketType,'bg')" borderColor="#fff"
              :color="bfColorStatus(item.ticketType,'color')" size="mini"
              :text="getDictDataLabel(DICT_TYPE.SYS_MC_VISIT_TYPE, item.ticketType)"></u-tag>
            <u-tag :bgColor="colorStatus(item.statusCode,'bg')" borderColor="#fff"
              :color="colorStatus(item.statusCode,'color')" size="mini" :text="item.statusName || '--'"></u-tag>
          </view>
        </view>
        <view class="margin-top-sm">
          <text class="text-grey margin-right-xs">工单编号:</text>{{item.ticketNumber || "--"}}
        </view>
        <view class="margin-top-sm">
          <text class="text-grey margin-right-xs">项目公司:</text>{{item.companyName|| "--"}}
        </view>
        <view class="margin-top-sm">
          <text class="text-grey margin-right-xs">收费人员:</text>{{item.billingPersonName}}
          - ({{getDictDataLabel(DICT_TYPE.SYS_MC_JOB_NATURE, item.jobNature) || "--"}})
        </view>
        <view class="margin-top-sm">
          <text class="text-grey margin-right-xs">用户:</text>{{item.userName|| "--"}}
        </view>
      </view>
      <view class="flex justify-end margin-top">
        <view class="margin-left-sm">
          <zb-popover placement="bottom-start" theme="dark" ref="Popover1" class="item-popover">
            <view slot="content" class="popoverCss">
              <view class="" v-if="publishChangePermission(item)">
                <view class="margin-tb-xs" @click="dataChange(item)">数据异动</view>
                <u-line></u-line>
              </view>
              <view class="">
                <view class="margin-tb-xs" @click="processFlow(item)">处理流程</view>
                <u-line></u-line>
              </view>
              <view class="" v-if="!!item.modificationStatus">
                <view class="margin-tb-xs" @click="changeFlow(item)">异动记录</view>
                <u-line></u-line>
              </view>
              <view class="" v-if="cancelPermission(item)">
                <view class="margin-tb-xs text-center" @click="giveUpVoid(item)">作废</view>
                <u-line></u-line>
              </view>
            </view>
            <u-button shape="circle">更多操作</u-button>
          </zb-popover>
        </view>
        <view class="margin-left-sm" @click="handleEdit(item)" v-if="editPermission(item)">
          <u-button shape="circle" type="primary">修改</u-button>
        </view>
        <view class="margin-left-sm" @click="handleDetail(item)" >
          <u-button shape="circle">查看详情</u-button>
        </view>
        <view class="margin-left-sm" @click="handleRefuse(item)" v-if="auditPermission(item)">
          <u-button shape="circle">拒绝</u-button>
        </view>
        <view class="margin-left-sm" @click="handleAgree(item)" v-if="auditPermission(item)">
          <u-button shape="circle" color="#CF000D">同意</u-button>
        </view>
      </view>
      <view class="nodeCss" v-if="item.statusCode === 'APPROVE'">
        {{item.statusNodeName}}
      </view>
    </view>
    <u-loadmore :status="status" v-if="list.length > 0" />
    <u-empty text="暂无资讯" icon="/static/images/icon/nodata.png" v-else></u-empty>

    <view  v-if="$checkPermi(['schsf:mcVisit:add'])" class="fixBtnCss" @click="createaVisit">
      <u-icon name="plus" color="#fff" size="30"></u-icon>
    </view>
    <popUpComponent :title="titles" :modificationStatus="modificationStatus" :publishID="publishID" :publishStatus="publishStatus" ref="popUpComponentRef"
      @getList="refreshList">
    </popUpComponent>
    <u-popup ref="bhPopup"></u-popup>
    <u-popup ref="bhPopup" :show="zfShow">
      <view class="popCss">
        <view class="padding-top text-lg text-center">
          作废
        </view>
        <view class="padding">
          <u-textarea v-model="zfRemarks" placeholder="请简单描述原因"></u-textarea>
        </view>
        <view class="flex justify-between">
          <view class="w50" @click="zfShow = false">
            <u-button>取消</u-button>
          </view>
          <view class="w50" @click="zfConfirm">
            <u-button :customStyle="{color:'#CF000D'}">确定</u-button>
          </view>
        </view>
      </view>
    </u-popup>
    <TabBar :currentPagePath="this.$route.meta.pagePath"></TabBar>
  </view>
</template>

<script>
  import {
    getMcVisitList,
    submitAuditOne,
    submitAuditTwo,
    submitModificationOne,
    submitModificationTwo,
    cancelMcVisit
  } from '@/api/charge.js'
  import popUpComponent from '@/components/popUpComponent/popUpComponent.vue'
  export default {
    components: {
      popUpComponent
    },
    props: {

    },
    data() {
      return {
        params: {
          pageNum: 1,
          pageSize: 10,
          userName: "",
          isMyAuditing: "",
        },
        status: "loadmore",
        list: [],
        total: null,
        title: "用户拜访/收费",
        keyword: "",
        moreShow: false,
        actionStyle: {
          'color': '#fff',
          'background': '#EC1E19',
          'borderRadius': "15px",
          'width': '60px',
          'height': '25px',
          'line-height': '25px',
        },
        loginOutShow: false,
        approvalValue: [],
        approval: [{
          name: "待我审批"
        }],
        titles: '同意',
        publishStatus: "",
        modificationStatus:"",
        publishID: 0,
        zfShow: false,
        zfRemarks: "",
        ZfId: "",
      }
    },
    computed: {

    },
    onReachBottom() {
      let allTotal = this.params.pageNum * this.params.pageSize
      if (allTotal < this.total) {
        //当前条数小于总条数 则增加请求页数
        this.params.pageNum++;
        this.status = 'loading';
        this.initData() //调用加载数据方法
      } else {
        this.status = "nomore"
        // console.log('已加载全部数据')
      }
    },
    onPullDownRefresh() {
      this.params.pageNum = 1;
      this.keyword = "";
      this.initData();
      setTimeout(() => {
        //结束下拉刷新
        uni.stopPullDownRefresh();
      }, 500);
    },
    onLoad() {
      // this.initData();
    },
    onShow(){
      this.initData();
    },
    methods: {
      // 修改按钮权限
      editPermission(item) {
        const { statusCode } = item
        return statusCode === 'EDITING' && this.$checkPermi(['schsf:mcVisit:edit'])
      },
      // 通过/驳回按钮权限(一级审核、二级审核、异动一级审批)
      auditPermission(item) {
        const { publishStatus, modificationStatus } = item;
        // 发起审核
        const auditPer = (publishStatus === 'PENDING_LEVEL_1_AUDIT' && this.$checkPermi(['schsf:mcVisit:ticket_submitAuditOne'])) ||
          (publishStatus === 'PENDING_LEVEL_2_AUDIT' && this.$checkPermi(['schsf:mcVisit:ticket_submitAuditTwo']))
        // 异动审核
        const changeAuditPer = publishStatus === 'APPROVED' &&
          ((modificationStatus === 'PENDING_LEVEL_1_AUDIT' && this.$checkPermi(['schsf:mcVisit:modification_submitAuditOne'])) ||
            modificationStatus === 'PENDING_LEVEL_2_AUDIT' && this.$checkPermi(['schsf:mcVisit:modification_submitAuditTwo']))

        return auditPer || changeAuditPer
      },
      // 发起异动权限
      publishChangePermission(item) {
        const { statusCode } = item;
        return statusCode === 'APPROVED' && this.$checkPermi(['schsf:mcVisit:modification'])
      },
      // 作废权限
      cancelPermission(item) {
        return (item.publishStatus === 'EDITING' || item.statusCode === 'APPROVED') && this.$checkPermi(['schsf:mcVisit:cancel'])
      },
      bfColorStatus(status, type) {
        const bgColorMap = {
          '3': '#EFF1FD',
          '2': '#FFF6E6',
          '1': '#E6F7F7',
          '0': '#F5F5F7',
        };
        const textColorMap = {
          '3': '#5875EB',
          '2': '#FFA500',
          '1': '#CF000D',
          '0': '#999DB0',
        };

        if (type === 'bg') {
          return bgColorMap[status] || '';
        } else if (type === 'color') {
          return textColorMap[status] || '';
        }
      },
      colorStatus(status, type) {
        const bgColorMap = {
          'APPROVE': '#EFF1FD',
          'EDITING': '#FAE6E7',
          'APPROVED': '#E6F7F7',
          'CANCEL': '#F5F5F7'
        };
        const textColorMap = {
          'APPROVE': '#5875EB',
          'EDITING': '#CF000D',
          'APPROVED': '#00AEAA',
          'CANCEL': '#999DB0'
        };

        if (type === 'bg') {
          return bgColorMap[status] || '';
        } else if (type === 'color') {
          return textColorMap[status] || '';
        }
      },
      refreshList() {
        this.params.pageNum = 1
        this.initData()
      },
      async initData() {
        let {
          code,
          rows,
          total
        } = await getMcVisitList(this.params);
        if (code === 200) {
          if (this.params.pageNum > 1) {
            this.list = [...this.list, ...rows]
          } else {
            this.list = rows;
          }
          this.total = total;
          console.log('list', JSON.parse(JSON.stringify(this.list)));
        }
      },
      viewDetail(item) {
        console.log('item', JSON.parse(JSON.stringify(item)));
      },
      onSearch(e) {
        this.params.userName = this.keyword;
        this.initData()
        console.log("搜索", e);
      },
      onClear(){
        this.keyword = "";
        this.params.userName = "";
        this.initData()
      },
      checkboxChange(e) {
        console.log(e);
        if (e.length) {
          this.params.isMyAuditing = "Y";
        } else {
          this.params.isMyAuditing = "其他";
        }
        this.initData();
      },
      handleDetail(item) {
        uni.navigateTo({
          url: '/pages/charge/visitsAndFees/detail?objData=' + JSON.stringify(item)
        })
      },
      // 拒绝按钮
      handleRefuse(item) {
        this.titles = "拒绝";
        this.publishStatus = item.publishStatus;
        this.modificationStatus = item.modificationStatus;
        this.publishID = item.id;
        this.$refs.popUpComponentRef.open();
      },
      // 同意按钮
      handleAgree(item) {
        console.log(item);
        this.publishStatus = item.publishStatus;
        this.publishID = item.id;
        this.modificationStatus = item.modificationStatus;
        this.titles = "同意";
        this.$refs.popUpComponentRef.open();
      },
      // 修改
      handleEdit(item) {
        let obj = JSON.stringify(item)
        uni.navigateTo({
          url: `/pages/charge/visitsAndFees/createaVisit?objData=${obj}&operation=edit`
        })
      },
      //创建拜访/收费
      createaVisit() {
        uni.navigateTo({
          url: '/pages/charge/visitsAndFees/createaVisit?operation=add'
        })
      },
      // 数据异动
      dataChange(item) {
        let obj = JSON.stringify(item)
        uni.navigateTo({
          url: `/pages/charge/visitsAndFees/createaVisit?objData=${obj}&operation=yd`
        })
      },
      // 处理流程
      processFlow(item) {
        let id = item.id;
        uni.navigateTo({
          url: `/pages/charge/visitsAndFees/processFlow?id=${id}&type=cllc`
        })
      },
      // 异动流程
      changeFlow(item) {
        let id = item.id;
        uni.navigateTo({
          url: `/pages/charge/visitsAndFees/processFlow?id=${id}&type=ydlc`
        })
      },
      // 作废
      giveUpVoid(item) {
        console.log("作废", item);
        this.ZfId = item.id;
        this.zfShow = true;
      },
      // 作废确定
      async zfConfirm(e) {
        console.log(e);
        let data = {
          id: this.ZfId,
          remarks: this.zfRemarks
        }
        console.log("作废数据", data);
        const result = await cancelMcVisit(data);
        if (result.code === 200) {
          uni.$u.toast('作废成功');
          this.initData();
        } else {
          uni.$u.toast(result.msg)
        }
        this.zfShow = false
      },
      loginOut() {
        this.$modal.confirm('您当前确定要退出吗?', '退出登录').then(() => {
          //钉钉直接退出微应用
          if (this.$isDing) {
            dd.biz.navigation.close({
              onSuccess: function(result) {
                console.log(result, 'result')
              },
              onFail: function(err) {
                console.log(err, 'err')
              }
            });
          } else {
            this.$store.dispatch('Logout').then((res) => {
              uni.reLaunch({
                url: '/pages/login/mobile'
              })
            })
          }
        }).catch(() => {
          console.log("取消");
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  /deep/.u-search__content {
    width: 70vw;
    padding-right: 140rpx;
  }

  /deep/.u-search__action {
    position: absolute;
    left: 50%;
  }

  .nodeCss {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 25rpx auto;
    border-radius: 20rpx;
    width: 95%;
    height: 80rpx;
    background: #EFF1FD;
    color: #5875EB;
    text-align: center;
  }


  .nodeCss::after {
    content: '';
    position: absolute;
    top: 0%;
    right: 25rpx;
    transform: translate(-50%, -50%) rotate(45deg);
    width: 10px;
    height: 10px;
    background: #EFF1FD;
    border: 1px solid #EFF1FD;
    border-style: none none solid solid;
  }

  .fixBtnCss {
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    width: 120rpx;
    height: 120rpx;
    position: fixed;
    background: #5875EB;
    right: 20rpx;
    bottom: 150rpx;
  }

  .popoverCss {
    padding: 20rpx;
    border-radius: 30rpx;
    color: #fff;
    background: #4C4C4C;
  }
</style>
