<template>
  <div>
    <div class="layout-content">
      <el-form
        :inline="true"
        :model="ruleForm"
        ref="ruleForm"
        class="demo-form-inline"
        label-position="right"
      >
        <el-form-item label="商铺号" prop="name" class="fx_title">
          <el-input v-model.trim="ruleForm.shopNumber" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="商户名称" prop="merchantName" class="fx_title">
          <el-input v-model.trim="ruleForm.merchantName" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="合同状态" class="fx_send">
          <el-select v-model="ruleForm.status" placeholder="请选择" clearable class="select-method">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审批状态" class="fx_send">
          <el-select v-model="ruleForm.applyStatus" placeholder="请选择" clearable class="select-method">
            <el-option
              v-for="(item,index) in applyStatusOptions"
              :key="index"
              :value="item.value"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            class="hoverBtn"
            type="primary"
            icon="el-icon-search"
            :style="'border:0;background:'+navigationInfo.moduleColor"
            @click="search"
          ></el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" class="builtBtn" @click="goSave">
        <i>+</i>新建
      </el-button>
      <!-- <el-button type="primary" class="builtBtn" @click="goRenew" style="margin-left:4px;">
        <i>+</i>续签
      </el-button> -->
      <table-list :ref="tk" :options="optionsTable"></table-list>
      <stop-contract :ref="st" :type='14' :processData="processData" :options="stopOptions"></stop-contract>
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="40%" :modal-append-to-body="false">
      <span>当前有欠缴账单未结清，是否要继续终止物业合同？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="stopContract">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import TableList from "../../../core/comps/table/tableList.vue";
import reportTool from "../../../core/tool/report.js";
import commonUtil from "../../../core/tool/commonUtil";
import AjaxUtil from "../../../core/tool/ajaxService";
import StopContract from "../contractutil/stopcontract.vue";
import { mapState, mapActions } from "vuex";
import { CouponCacheData } from "../../../service/couponData/data.js";
import { ContractData } from "../../../service/contract/data.js";
import { promissionUrl } from "../../../urlconfig/promission/url.js";
import { ContractUrl } from "../businessComp/UrlEnum.js";
let echarts = require("echarts");
export default {
  inject: ["reload"],
  extends: AjaxUtil,
  name: "tenementlist",
  components: {
    TableList,
    StopContract
  },
  data() {
    return {
      processData:[],
      waitSignCount: "", //待签约
      endSoonCount: "", //将到期合同
      rendPaidCount: "", //计租中合同
      shopcount: "", //空余商铺
      tk: "manjianTableKey",
      st: "stopContract",
      stopOptions: {
        contractType: "3",
        stopType: 2 //物业合同
      },
      applyStatusOptions:ContractData.applyStatus,
      ruleForm: {
        shopNumber: "",
        merchantName: "",
        status:"",
        applyStatus:''
      },
      options:ContractData.statusOptions,
      dialogVisible: false,
      optionsTable: {
        actions: [
          {
            key: "edit",
            val: "提交审批",
            action: this.doApply,
            show: item => {
              return item.status == 1
                ? true
                : false;
            }
          },
          {
            key: "edit",
            val: "编辑",
            action: this.goEdit,
            show: item => {
              return item.status == 10 && (item.applyStatus == 3 || item.applyStatus == 5)
                ? true
                : false;
            }
          },
          {
            key: "edit",
            val: "终止",
            action: this.endcontract,
            // show: this.isendcontract(item),
            show: item => {
              if (
                item.status == 2 || item.status == 3
              ) {
                return true;
              } else {
                return false;
              }
            }
          },
          {
            key: "edit",
            val: "查看",
            action: this.goCheck,
            show: item => {
              return true;
            }
          },
          {
            key: "download",
            val: "下载",
            action: this.goDownload,
            show: item => {
              return true;
            }
          },
          {
            key: "edit",
            val: "审批进度",
            action: this.checkCurrentStatus,
            show: item => {
              return item.applyStatus == 1 ||
                item.applyStatus == 2 ||
                item.applyStatus == 3 || 
                item.applyStatus == 5
                ? true
                : false;
            }
          }
        ],
        showCk: false,
        map: [
          {
            key: "contractNumber",
            val: "合同编号"
          },
          {
            key: "shopNumber",
            val: "商铺号",
            convert: this.changeShopNum,
            sortable:true
          },
          {
            key: "merchantName",
            val: "商户名称"
          },
          {
            key: "rentalStartDate",
            val: "租赁开始日期",
            type: "date",
            sortable:true
          },
          {
            key: "rentalEndDate",
            val: "租赁结束日期",
            type: "date",
            sortable:true
          },
          {
            key: "price",
            val: "物业费",
            convert: this.divide,
            sortable:true
          },

          {
            key: "status",
            val: "合同状态",
            convert: this.cStatus
          },
          {
            key: "applyStatus",
            val: "审批状态",
            convert: this.cApplyStatus
          }
        ],
        getUrl: () => {
          return (
            "/api/wxPropertyContract/list?merchantName=" +
            this.ruleForm.merchantName +
            "&shopNumber=" +
            this.ruleForm.shopNumber +
            "&rentShopType=1&applyStatus=" +
            this.ruleForm.applyStatus +
            "&status=" +
            this.ruleForm.status+
            "&operationType=1"
          );
        },

        pageOption: {
          sizeKey: "pageSize",
          indexKey: "pageNum",
          index: 1,
          size: 10
        },
        analysis: data => {
          return {
            data: data.data.pageInfo.list,
            count: data.data.pageInfo.total
          };
        }
      }
    };
  },
  computed: {
    ...mapState({
      navigationInfo: state => state.topNav.navigationInfo
    })
  },
  methods: {
    ...mapActions([
      "setNavData" // 将this.setNavData 映射为 this.$store.dispatch('setNavData')
    ]),
    doApply(item,row) {
      console.log(item)
      let params = {
        remark: '',
        id: item.id
      }
      this.postFetch("/api/wxRentContract/apply",params)
        .then(d => {
          
        })
        .catch(err => {
          this.$message.success(err.data);
        });
    },
    changeShopNum(item, row) {
      let rentInfo = row.rentInfo?JSON.parse(row.rentInfo):[];
      let str = "";
      rentInfo.map((items, indexs) => {
        str = str != "" ? str + " ," + items.shopNumber : items.shopNumber;
      });
      return str;
    },
    cApplyStatus(col, item) {
      if (item.applyStatus) {
        return (
          (item.businessType != 14 ? "签约" : "终止") +
          ContractData.applyStatus.filter(e => e.value == item.applyStatus)[0]
            .name
        );
      } else if (item.applyStatus === 0) {
        return "未提交审核";
      }
    },
    checkCurrentStatus(item, row) {
      this.$router.push({
        path: "rentApprovals?id=" + item.id
      });
    },
    cStatus(col, item) {
      return CouponCacheData.rentStatus.filter(e => {
        return e.value == item.status.toString();
      })[0].name;
    },
    goEdit: function(item, row) {
      this.$router.push({
        path: "tenementAdd?id=" + item.id
      });
    },
    divide(col, item) {
      return Number(item.price) / 100 +(item.price_unit==1?'元/日':item.price_unit==2?'元/月':'元/年');
    },
    endcontract: function(item, row) {
      let that = this;
      that.contractId = item.id;
      that.contractNumber = item.contractNumber;
      this.getFetch("/api/wxBillAll/oweBillCount?type=2&contractId=" + item.id)
        .then(d => {
          if (Number(d.data) > 0) {
            that.dialogVisible = true;
          } else {
            if(this.processData.length>0){
              this.dialogVisible = false;
              this.$refs[this.st].showLog(this.contractId, this.contractNumber);
            }else{
              this.makeSure();
            }
          }
        })
        .catch(err => {
          this.$message.success(err.data);
        });
    },
    stopContract() {
      // this.$refs[this.st].showLog(this.contractId, this.contractNumber);
      if(this.processData.length>0){
        this.dialogVisible = false;
        this.$refs[this.st].showLog(this.contractId, this.contractNumber);
      }else{
        this.endProperty();
      }
    },
    makeSure(){
      this.$confirm('您确定要提前终止此合同吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.endProperty();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    endProperty(){
      let _this=this;
      let param={
        id:this.contractId
      }
      this.postFetch(ContractUrl.endPropertyContract, param)
        .then(d => {
          _this.$message.success("操作成功");
          _this.dialogVisible = false;
          _this.search();
        })
        .catch(err => {
          this.$message.error(err.data);
        });
    },
    goSave: function() {
      this.$router.push({
        path: "/tenementAdd"
      });
    },
    goRenew(){
       this.$router.push({
        path: "/tenementAdd",
        query:{
          Renew:true
        }
      });
    },
    goCheck: function(item, row) {
      /**
        contractType合同类型：1租金合同,2多经合同,3物业合同,4多经物业合同
        businessType操作类型：1合同审批,2账单审批,3终止合同审批
        id为合同id
       */
      this.$router.push({
        path: `rentsCheck?id=${item.id}&contractType=3&businessType=1`
      });
    },
    getcount: function() {
      this.getFetch(
        "/api/wxPropertyContract/list?pageNum=1&pageSize=10&shopNumber=" +
          this.ruleForm.shopNumber +
          "&merchantName=" +
          this.ruleForm.merchantName +
          "&rentShopType=1"
      )
        .then(d => {
          this.waitSignCount = d.data.rentContractStatusInfo.waitSignCount;
          this.endSoonCount = d.data.rentContractStatusInfo.endSoonCount;
          this.rendPaidCount = d.data.rentContractStatusInfo.rendPaidCount;
          this.shopcount =
            d.data.rentContractStatusInfo.shopCountInfo.unrentedCount; //空余商铺
          let allRentCount =
            Number(d.data.rentContractStatusInfo.allCount) == 0
              ? 100
              : Number(d.data.rentContractStatusInfo.allCount); //合同总数
          let allShopCount =
            Number(d.data.rentContractStatusInfo.shopCountInfo.allCount) == 0
              ? 100
              : Number(d.data.rentContractStatusInfo.shopCountInfo.allCount); //商铺总数

          let value_spare = Number(this.shopcount) || 0;
          let myChart_spare = echarts.init(document.getElementById("spare"));
          myChart_spare.setOption(
            reportTool.myPie("空余商铺", "#5976BF", value_spare, allShopCount)
          );

          let value_signed = Number(this.waitSignCount) || 0;
          let myChart_signed = echarts.init(document.getElementById("signed"));
          myChart_signed.setOption(
            reportTool.myPie("待签约", "#C85963", value_signed, allRentCount)
          );

          let value_expire = Number(this.endSoonCount) || 0;
          let myChart_expire = echarts.init(document.getElementById("expire"));
          myChart_expire.setOption(
            reportTool.myPie("将到期", "#EE7653", value_expire, allRentCount)
          );

          let value_planning = Number(this.rendPaidCount) || 0;
          let myChart_planning = echarts.init(
            document.getElementById("planning")
          );
          myChart_planning.setOption(
            reportTool.myPie("计租中", "#3FC496", value_planning, allRentCount)
          );
        })
        .catch(err => {
          this.$message.error(err.data);
        });
    },
    search: function() {
      let tk = this.$refs[this.tk];
      tk.search(tk.getParams().index);
    },
    goDownload: function(item) {
      location.href =
        "/api/wxRentContract/exportContract?id=" + item.rentContractId;
    },
    /**
     * 根据业务查询模板
     */
    getModelBybusiness(){
      this.getFetch(`${promissionUrl.getModelBybusiness}?flowType=14`)
      .then(d=>{
        if(d.data.length>0){
          this.processData = JSON.parse(d.data[0].flow).lists;
        }
      })
      .catch(err=>{
        this.$message.error(err.data);
      })
    }
  },
  created(){
    this.setNavData(["合同管理", "店铺", "物业合同"]);
  },
  activated(){
    this.search()
    // this.getcount();
    this.getModelBybusiness();
    this.setNavData(["合同管理", "店铺", "物业合同"]);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.layout-content {
  width: 100%;
  background: #141e29;
  height: auto;
  border-radius: 2px;
  min-height: 300px;
  padding: 0 20px 20px 20px;
  overflow: hidden;
  text-align: left;
}
.el-form {
  background: #f5f7f8;
  text-align: left;
  padding: 25px 22px 22px;
  margin-bottom: 20px !important;
}
.el-form .el-form-item {
  margin-bottom: 0 !important;
}
.tableContainer {
  margin-top: 20px !important;
  background: #fff;
}
.el-button {
  width: 60px;
  height: 40px;
}
.builtBtn {
  width: 100px;
  height: 32px;
  background: rgba(81, 169, 201, 1);
  border: 0 !important;
  line-height: 32px;
  text-align: center;
  margin: 0;
  padding: 0 !important;
}
.builtBtn:hover {
  background: rgba(81, 169, 201, 0.88);
}
.builtBtn i {
  margin-right: 10px;
}
.el-form-item .el-form-item__content,
.el-form-item .el-form-item__content .el-date-editor,
.el-form-item .el-form-item__content .el-date-editor .el-input__inner {
  width: 150px;
}
.fx_title .el-input {
  width: 193px;
}
</style>