<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="">
			<uv-drop-down ref="dropDown" sign="dropDown_1" :customStyle="{'justifyContent':'space-around'}"
				: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="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="topSelectCss">
      <view class="flex justify-around">
        <view class="flex align-center" v-for="(item,index) of searchList" @click="openPicker(item)" :key="item.title">
          <view class="text-lg">
            <span v-if="searchForm[item.name]" class="text-red">
              {{searchForm[item.name]}}
            </span>
            <span v-else>{{ item.title }}</span>
          </view>
          <view class="margin-left-xs" v-if="item.title == '财年'">
            <u-icon name="calendar-fill" size="25"></u-icon>
          </view>
          <view class="margin-left-xs" v-else>
            <u-icon v-if="currentName == item.key" color="#5875eb" name="arrow-up-fill" size="12"></u-icon>
            <u-icon v-else name="arrow-down-fill" color="#999db0" size="12"></u-icon>
          </view>
        </view>
      </view>
    </view>

    <view class="usuallyCard margin padding" v-if="list.length" v-for="(item,index) in list" :key="index">
      <view class="flex flex-direction">
        <view class="flex justify-between">
          <view class="">
            <text class="text-grey margin-right-xs">项目公司:</text>{{item.companyName || '--'}}
          </view>
          <view class="flex">
            <!-- <u-tag bgColor="#EFF1FD" borderColor="#fff" color="#5875EE" size="mini" text="待审批"></u-tag> -->
          </view>
        </view>
        <view class="margin-top-sm">
          <text class="text-grey margin-right-xs">村(小区):</text>{{item.vlgOrCmty || '--'}}
        </view>
        <view class="margin-top-sm">
          <text class="text-grey margin-right-xs">项目类型:</text>{{item.projectTypeName || '--'}}
        </view>
      </view>
      <view class="flex justify-end margin-top">
        <view class="margin-right-xs">
          <u-button shape="circle" @click="handleDetail(item)">查看详情</u-button>
        </view>
        <view class="margin-right-xs" v-if="item.gasConnMtrRis =='W'">
          <u-button :disabled="item.projectTypeCode == '0' || item.isCompleted!=='W'" shape="circle" color="#CF000D"
            @click="handleOpen(item,'gcwh','工程维护')">工程维护</u-button>
        </view>
        <view class="margin-right-xs" v-if=" item.gasConnMtrRis !=='W'">
          <u-button :disabled="item.projectTypeCode == '0' || item.isCompleted =='W'" shape="circle" color="#CF000D"
            @click="handleOpen(item,'gcwh','工程变更')">工程变更</u-button>
        </view>
        <view class="margin-right-xs" v-if="item.gasConnMtrRis =='W'">
          <u-button :disabled="item.projectTypeCode == '0'||item.isCompleted=='W' || item.gasConnMtrRis!=='W'"
            shape="circle" color="#CF000D" @click="handleOpen(item,'yywh','运营维护')">运营维护</u-button>
        </view>
        <view class="margin-right-xs" v-if="item.gasConnMtrRis !=='W'">
          <u-button :disabled="item.projectTypeCode == '0' || item.gasConnMtrRis=='W'" shape="circle" color="#CF000D"
            @click="handleOpen(item,'yywh','运营变更')">运营变更</u-button>
        </view>
      </view>
      <!-- <view class="nodeCss">
				当前审批节点：项目公司_市场负责人
			</view> -->
    </view>
    <u-loadmore :status="status" v-if="list.length > 0" />
    <u-empty text="暂无数据" icon="/static/images/icon/nodata.png" v-else></u-empty>
    <popUpFillIn  :itemData="itemData" :type="btnType" :title="title" ref="popUpFillInRef"
      @getList="initData">
    </popUpFillIn>

    <!-- 字典下拉 -->
    <u-picker :show="pickerShow" ref="uPicker" closeOnClickOverlay :columns="columns" @cancel="selectCancel"
      @close="selectCancel" keyName="label" @confirm="selectConfirm"></u-picker>
    <!-- 公司下拉-->
    <u-picker :show="gsShow" ref="gsPicker" :title="gsName" closeOnClickOverlay :columns="companyList"
      @cancel="gsCancel" @close="gsCancel" keyName="label" @confirm="gsConfirm" @change="changeHandler"></u-picker>
    <!-- 时间下拉开始 -->
    <TabBar :currentPagePath="this.$route.meta.pagePath"></TabBar>
  </view>
</template>

<script>
  import {
    getCompanyCascader,
    getMcConstructionList
  } from '@/api/charge.js'
  import * as dd from 'dingtalk-jsapi'
  export default {
    components: {},
    props: {

    },
    data() {
      return {
        title: "",
        keyword: "",
        actionStyle: {
          'color': '#fff',
          'background': '#EC1E19',
          'borderRadius': "15px",
          'width': '60px',
          'height': '25px',
          'line-height': '25px',
        },
        btnType: "gcwh",
        params: {
          pageNum: 1,
          pageSize: 10,
          companyCode: "",
          isCompleted: "",
          gasConnMtrRis: ""
        },
        status: "loadmore",
        list: [],
        total: null,
        itemData: {},
        searchForm: {
          companyCode: "",
          isCompleted: "",
          gasConnMtrRis: ""
        },
        model: {},
        currentName: "",
        userCode: "",
        gsShow: false,
        pickerShow: false,
        columns: [],
        companyOption: [],
        regionName: [],
        groupName: [],
        companyName: [],
        gsName: "",
        searchList: [{
            title: '项目公司',
            name: 'companyCode',
            type: 'select',
            key: 'company',
          },
          {
            title: '是否竣工',
            name: 'isCompleted',
            type: 'select',
            key: 'isCompleted',
            dict: 'sys_cn_yn'
          },
          {
            title: '是否通气到表前',
            name: 'gasConnMtrRis',
            type: 'select',
            key: 'gasConnMtrRis',
            dict: 'sys_cn_yn'
          },
        ]
      }
    },
    computed: {
      companyList() {
        return [this.regionName, this.groupName, this.companyName];
      }
    },
    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,
        pageSize: 10,
      }
      this.searchForm = {}
      this.keyword = "";
      this.initData();
      setTimeout(() => {
        //结束下拉刷新
        uni.stopPullDownRefresh();
      }, 500);
    },
    onLoad() {
      this.initData();
      this.getCompanyCascader();
    },
    onShow() {
      // this.initData();
    },
    methods: {
      async initData() {
        let {
          code,
          rows,
          total
        } = await getMcConstructionList(this.params);
        if (code === 200) {
          if (this.params.pageNum > 1) {
            this.list = [...this.list, ...rows]
          } else {
            this.list = rows;
          }
          this.total = total;
          if (this.total < this.params.pageNum * this.params.pageSize) {
            this.status = "nomore"
          }
          console.log('list', JSON.parse(JSON.stringify(this.list)));
        }
      },
      async getCompanyCascader() {
        this.companyOption = (await getCompanyCascader()).data;
        this.companyOption.forEach(item1 => {
          this.regionName.push(item1);
          item1.children.forEach(item2 => {
            this.groupName.push(item2);
            item2.children.forEach(item3 => {
              this.companyName.push(item3);
            });
          });
        });
        console.log("当前公司类", this.companyOption);
      },
      async openPicker(data) {
        console.log("下拉data", data)
        this.currentName = data.key;
        console.log('打印data-===', data);
        if (data.type === 'select') {
          if (data.key == 'company') {
            this.gsColumns = [this.regionName, this.groupName, this.companyName];
            this.gsName = `${this.regionName[0].label}`;
            this.gsShow = true;
          } else {
            let dict = data.dict;
            let dictArr = this.getDictDatas(dict);
            this.columns = [dictArr];
            this.pickerShow = true;
          }
        } else {
          console.log('打印data===', data);
          this.datetimeShow = true;
          // this.showTimeParams.showStartDailog = true;
        }
      },
      // 项目公司切换
      changeHandler(e) {
        const {
          columnIndex,
          value,
          values, // values为当前变化列的数组内容
          index,
          indexs
          // 微信小程序无法将picker实例传出来，只能通过ref操作
        } = e
        console.log(e);
        // 当第一列值发生变化时，变化第二列(后一列)对应的选项
        let [regionIndex, groupIndex, companyIndex] = indexs;
        if (columnIndex === 0) {
          this.gsName = value[0].label;
          console.log(0, this.regionName)
          // this.regionName = this.regionName[index]?.children || [];
          this.groupName = this.regionName[index]?.children || [];
          this.companyName = this.groupName[0]?.children || [];
          console.log(1, this.regionName)
          console.log(2, this.groupName)
          console.log(3, this.companyName)
          this.$refs.gsPicker.setIndexs([index, 0, 0], true)
        } else if (columnIndex === 1) {
          this.gsName = value[1].label;
          this.groupName = this.regionName[index]?.children || [];
          this.companyName = this.groupName[0]?.children || [];
          this.$refs.gsPicker.setIndexs(indexs, true)
        } else if (columnIndex === 2) {
          this.gsName = value[2].label;
        }
        // let data2 = value[0].children;
        // let data3 = data2[0].children;
        // picker为选择器this实例，变化第二列对应的选项
        // this.gsColumns = [this.regionName, data2, data3]
        console.log("选择后", this.gsColumns);
      },
      selectConfirm(e) {
        let data = e.value[0].value;
        let dataLabel = e.value[0].label;
        if (this.currentName === 'isCompleted') {
          this.searchForm.isCompleted = dataLabel;
          this.model.isCompleted = data;
          this.params.isCompleted = data === '是' ? 'Y' : 'N';
        } else if (this.currentName === 'gasConnMtrRis') {
          this.searchForm.gasConnMtrRis = dataLabel;
          this.model.gasConnMtrRis = data;
          this.params.gasConnMtrRis = data === '是' ? 'Y' : 'N'
        }
        this.pickerShow = false;
        this.currentName = '';
        this.list = [];
        this.initData()
      },
      selectCancel(e) {
        this.pickerShow = false;
        this.currentName = '';
      },
      gsConfirm(e) {
        console.log("公司", e);
        this.model.regionName = e.value[0]?.value;
        this.model.groupName = e.value[1]?.value;
        this.model.companyName = e.value[2]?.label;
        this.model.companyCode = e.value[2]?.value;
        this.gsShow = false;
        this.searchForm.companyCode = this.model.companyName.slice(0, 5) + '...';
        this.params.companyCode = this.model.companyCode;
        this.list = [];
        this.initData();
        this.currentName = '';
      },
      gsCancel() {
        this.gsShow = false;
        this.currentName = '';
      },
      // 查看详情
      handleDetail(item) {
        uni.navigateTo({
          url: '/pages/charge/constructionMaintenance/detail?objData=' + JSON.stringify(item)
        })
      },
      handleOpen(item, type, name) {
        console.log("item",item)
        this.title = name;
        this.itemData = item;
        // this.IgnitionID = item.id;
        this.btnType = type;
        this.$refs.popUpFillInRef.open();
      },
      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;
  }

  .topSelectCss {
    padding: 10px 20px;
    background: #fff;
  }
</style>
