<template>
  <div>
    <el-card class="el-card">
      <el-form :model="filterQuery" class="query-form" label-width="100px" v-if="showSearch">
        <el-row>
          <el-col :span="6">
            <el-form-item label="合同编号">
              <el-input v-model="filterQuery.code" style="width: 90%" placeholder="请输入合同编号" clearable></el-input>
            </el-form-item>
          </el-col>


          <el-col :span="6">
            <el-form-item label="合同名称">
              <el-input v-model="filterQuery.name" style="width: 90%" clearable placeholder="请输入合同名称">
              </el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :span="10">-->
<!--            <el-form-item label="合同状态：" prop="emergency">-->
<!--              <el-select v-model="filterQuery.status" placeholder="请选单据状态" style="width: 90%" @change="getList" clearable>-->
<!--                <el-option label="草稿" :value='0'></el-option>-->
<!--                <el-option label="审核中" :value='1'></el-option>-->
<!--                <el-option label="已审核" :value='2'></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="合同签订日期:">
              <el-date-picker
                :picker-options="pickerOptions"
                v-model="actDateRange"
                type="daterange"
                format="yyyy 年 MM 月 dd 日"
                style="width: 90%"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div class="top-right-btn">
        <el-button-group style="display:flex;">
          <el-button icon="el-icon-view" type="primary" @click="hideSearch">显示/隐藏搜索栏</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="onSubmitFind">查询</el-button>
<!--          <el-button type="primary" icon="el-icon-plus" @click="newDistributionForm()" :loading="loading">新增合同 </el-button>-->
<!--          <el-button type="primary" icon="el-icon-plus" @click="newDistributionFormPlan()" :loading="loading">导入计划-->
<!--          </el-button>-->
        </el-button-group>
      </div>
      <el-divider style="margin: 15px"></el-divider>

      <el-table v-loading="loading" :data="list" style="width: 100%" border highlight-current-row
                @current-change="handleDetail" :default-sort="defaultSort" @sort-change="handleSortChange">
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="合同编号" prop="code"></el-table-column>
        <el-table-column label="合同名称" prop="name"></el-table-column>
        <el-table-column label="往来单位/供应商" prop="fromCorp"></el-table-column>
        <el-table-column label="合同仓库" prop="invCode" :formatter="invCodeFormat"></el-table-column>

        <el-table-column label="合同状态" prop="status" >
          <template slot-scope="scope" >
            <el-tag :type="(scope.row.status == 0? 1:scope.row.status ) | statusFilterType" v-if="scope.row.approvalFlowId == null" >
              {{ statusMap[(scope.row.status == 0? 1:scope.row.status ) ] }}
            </el-tag>
            <el-tag :type="(scope.row.flowStatus == 0? 1:scope.row.flowStatus ) | statusFilterType" v-if="scope.row.approvalFlowId != null">
              {{ statusMap[(scope.row.flowStatus == 0? 1:scope.row.flowStatus ) ] }}
            </el-tag>
            <el-tag v-if="scope.row.nextNodeName !=  null && scope.row.nextNodeName != '' && scope.row.flowStatus == 2 && scope.row.approvalFlowId != null" class="tag-right-align">
              <b v-if="scope.row.nextApprovalNodeType == 1">待人员</b>
              <b v-if="scope.row.nextApprovalNodeType == 2">待岗位</b>
              【{{ scope.row.nextNodeName }}】审核
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="合同类型" prop="type" :formatter="typeFormat"></el-table-column>
<!--        <el-table-column label="付款方式" prop="payType" :formatter="payTypeFormat"></el-table-column>-->
        <el-table-column label="付款方式" prop="payType"></el-table-column>

        <el-table-column label="合同签订日期" prop="contractDate"
                         sortable="custom" :sort-orders="['ascending', 'descending']"></el-table-column>
        <el-table-column label="备注" prop="remark"></el-table-column>

        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.native="newDistributionForm(scope.$index, scope.row)" v-show="(scope.row.status=='' || scope.row.status == 1) ">编辑
            </el-button>
            <el-button type="text" size="small" @click.native.stop="deleteDialog(scope.row)" v-show="(scope.row.status=='' || scope.row.status==1) " >删除</el-button>

            <el-button type="text" size="small" @click.native.stop="showApprovalFlowDetail(scope.row)"
                       v-show=" scope.row.status != 1 && scope.row.status !='' && scope.row.approvalFlowId != null  ">审批详情
            </el-button>

          </template>
        </el-table-column>
      </el-table>


      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="filterQuery.page"
        :limit.sync="filterQuery.limit"
        @pagination="handleCurrentChange"

      ></pagination>
    </el-card>
    <el-card class="el-card">
      <el-table v-loading="loading" :data="detailList" style="width: 100%" border highlight-current-row>
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="DI/物资编码" prop="nameCode"></el-table-column>
        <el-table-column label="产品名称" prop="productName"></el-table-column>
        <el-table-column label="生产厂家" prop="productCompany"></el-table-column>
        <el-table-column label="注册证/备案号" prop="zczbhhzbapzbh"></el-table-column>
        <el-table-column label="规格型号" prop="ggxh"></el-table-column>
        <el-table-column label="包装级别" prop="packRatio"></el-table-column>
        <el-table-column label="供应商名称" prop="supName"></el-table-column>
        <el-table-column label="数量" prop="count"></el-table-column>
      </el-table>

      <pagination
        v-show="detailquery.total>0"
        :total="detailquery.total"
        :page.sync="detailquery.page"
        :limit.sync="detailquery.limit"
        @pagination="handleCurrentChangeDetail"

      ></pagination>
    </el-card>

    <el-dialog
      :title="formMap[formName]"
      :visible.sync="newSpDistributionVisible"
      width="80%"
      v-if="newSpDistributionVisible"
      @close='closeDialog'
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <purContractEdit
        :isChang="isChang"
        :closeDialog="closeDialog"
        v-on:cancelDialog="getId"
        :idQuery="idQuery"
      ></purContractEdit>
    </el-dialog>

    <el-dialog
      :title="formMap[formName]"
      :visible.sync="newDistributionFormPlanVisible"
      width="80%"
      v-if="newDistributionFormPlanVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <purContractSelectPlan
        :invList = "this.invList"
        :closeDialog="closeDialogSp"
      ></purContractSelectPlan>
    </el-dialog>



    <el-dialog
      title="审批详情"
      :visible.sync="approvalFlowDetailVisible"
      width="65%"
      v-if="approvalFlowDetailVisible"
      @close='closeDialog'
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <approvalFlowDetail
        :isChang="true"
        :closeDialog="closeDialog"
        :idQuery="idQuery"
      ></approvalFlowDetail>
    </el-dialog>



  </div>
</template>
<script>
import approvalFlowDetail from "@/components/ApprovalFlow";
import purContractEdit from "@/views/purchase/purContract/purContractEditDialog";
import purContractSelectPlan from "@/views/purchase/purContract/purContractSelectPlan";
import {delApply, inserThrOrderWeb, listPlan, listApplyDetail, delContractDetailAll} from "@/api/purchase/purContract";
// import {filterAllByUser} from "@/api/basic/invWarehouse";

export default {
  name: "purContract",
  data() {
    return {
      pageType:null,
      defaultSort: {prop: 'createTime', order: 'desc'},
      showSearch: true,
      pId: null,
      isChang: false,
      filterQuery: {
        billAction: null,
        billNo: "",
        originType: null,
        thirdSysFk: "",
        page: 1,
        limit: 10,
        corpName: null,
        type: 1,
        status: 12,
        editStatus: 1,
        emergency: '',
        deptCode: '',
        invCode: null,
        pageType: this.$route.query.pageType
      },
      invCodebe: null,
      formName: null,
      formMap: {
        add: "新增合同信息",
        update: "编辑合同信息",
        selectPlan: "选择采购计划",
      },
      statusMap: {
        1: "草稿",
        2: "审核中",
        3: "通过",
        4: "拒绝"
      },
      typeList:[
        {name: '战略' ,code: 1 },
        {name: '长期' ,code: 2 },
        {name: '短期' ,code: 3 }
      ],
      statusList:[
        {name: '草稿' ,code: 1 },
        {name: '未审核' ,code: 2 },
        {name: '已审核' ,code: 3 }
      ],
      payTypeList:[
        {name: '银行' ,code: 1 },
        {name: '微信' ,code: 2 },
        {name: '支付宝' ,code: 3}
      ],
      idQuery: {},
      row: {},
      total: 0,
      thirdSys: [],
      thirdSysDetail: null,
      busTypes: [],
      originTypes: [],
      list: [],
      detailList: [],
      loading: false,
      actDateRange: [],
      emergencyMap: {
        1: "正常",
        2: "较急",
        3: "特急",
      },
      detailquery:
        {
          orderIdFk: null,
          total: 0,
          page: 1,
          limit: 10,
        },
      invList: {},
      deptList: {},
      newSpDistributionVisible: false,
      newDistributionFormPlanVisible: false,
      approvalFlowDetailVisible: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },

  methods: {
    showApprovalFlowDetail(row) {
      this.idQuery.approvalFlowId = row.approvalFlowId
      this.approvalFlowDetailVisible = true;
    },
    invCodeFormat(row) {
      let obj = ''
      this.invList.forEach((item) => {
        //循环list，如果数据相等return出去就好了
        //不会影响原来的数据，只是展示出来的是name
        if (row.invCode == item.code) {
          obj = item.name
        }
      })
      return obj
    },
    statusFormat(row) {
      let obj = ''
      this.statusList.forEach((item) => {
        //循环list，如果数据相等return出去就好了
        //不会影响原来的数据，只是展示出来的是name
        if (row.status == item.code) {
          obj = item.name
        }
      })
      return obj
    },
    typeFormat(row) {
      let obj = ''
      this.typeList.forEach((item) => {
        //循环list，如果数据相等return出去就好了
        //不会影响原来的数据，只是展示出来的是name
        if (row.type == item.code) {
          obj = item.name
        }
      })
      return obj
    },
    payTypeFormat(row) {
      let obj = ''
      this.payTypeList.forEach((item) => {
        //循环list，如果数据相等return出去就好了
        //不会影响原来的数据，只是展示出来的是name
        if (row.payType == item.code) {
          obj = item.name
        }
      })
      return obj
    },
    onReset() {
      this.filterQuery = {
        billNo: "",
        thirdSysFk: "",
        billFlag: null,
        billAction: null,
        startDate: null,
        endDate: null,
        page: 1,
        limit: 10,
        corpName: null,
        type: 1,
        status: 12,
        editStatus: 1,
        deptCode: this.invCodebe,
        invCode: null,
        pageType: this.pageType
      };
      this.actDateRange = [];
      this.getInvList()
      this.getList();
    },
    handleClose() {
      this.approvalFlowDetailVisible = false;
      if (this.formName == 'add') {
        this.isChang = !this.isChang
      } else {
        this.newSpDistributionVisible = false
      }
      this.getList();
    },
    getId(id) {
      if (this.formName == 'add' && id != null) {
        var data = {
          id: id
        }
        this.pId = id;
        //当在新增时取消添加操作删除掉这次的数据
        delContractDetailAll(data).then((response) => {
          if (response.code == 20000) {
            this.newSpDistributionVisible = false
          }
        });
      } else {
        this.newSpDistributionVisible = false
      }

    },
    onSubmitFind() {
      this.filterQuery.page = 1;
      this.getList();
    },
    hideSearch() {
      this.showSearch = !this.showSearch;
    },

    handleSortChange(column, prop, order) {
      if (column.order === 'descending') {
        this.filterQuery.sort = 'desc'
      } else {
        this.filterQuery.sort = 'asc'
      }
      this.filterQuery.orderBy = column.prop;
      this.getList();
    },


    getList() {
      if (this.actDateRange != null) {
        this.filterQuery.startDate = this.actDateRange[0];
        this.filterQuery.endDate = this.actDateRange[1];
      } else {
        this.filterQuery.startDate = null;
        this.filterQuery.endDate = null;
      }
      if (this.filterQuery.status == null) {
        this.$message.warning("单据状态不可为空！");
        return;
      }
      this.loading = true;
      listPlan(this.filterQuery).then((response) => {
        if (response.code == 20000) {
          this.list = response.data.list || [];
          this.total = response.data.total || 0;
          this.detailList = []
        } else {
          this.$message.error(response.message);
        }
        this.loading = false;
      })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    handleDetail(row) {
      if (row.id == null) {
        this.row = this.list[0]
        this.detailquery.orderIdFk=this.row.id
      }else {
        this.detailquery.orderIdFk=row.id
      }

      this.loading = true;
      listApplyDetail(this.detailquery) //查找该单号下的所有条码
        .then((response) => {
          this.detailList = response.data.list || [];
          this.detailquery.total = response.data.total || 0;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.detailList = [];
          this.total = 0;
        });
    },
    submitOrder(row) {
      this.$confirm("是否确定提交审核?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          let tQuery = {
            editStatus: 2,
            purPlanEntity: row,
          }
          inserThrOrderWeb(tQuery)
            .then(response => {
              this.loading = false;
              if (response.code === 20000) {
                this.$message.success("提交成功！");
                this.getList();
              } else {
                this.$message.error(response.message);
              }
            })
            .catch(() => {
              this.loading = false;
            })
        })
        .catch(() => {
        });
    },
    deleteDialog(row) {
      this.$confirm("此操作将永久删除该单据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delContractDetailAll({id: row.id})
            .then((response) => {
              this.loading = false;
              if (response.code == 20000) {
                this.$message.success("删除成功");
                this.getList();
              } else {
                this.$message.error(response.message);
              }
            })
            .catch(() => {
              this.loading = false;
            });

        })
        .catch(() => {
        });
    },
    handleCurrentChange(val) {
      this.filterQuery.page = val.page;
      this.getList();
    },
    handleCurrentChangeDetail(val) {
      this.detailquery.page = val.page;
      this.handleDetail(this.row)
    },
    closeDialog() {
      this.approvalFlowDetailVisible = false;
      this.newSpDistributionVisible = false;
      this.getList();
      this.detailList = [];
    },
    closeDialogSp() {
      this.newDistributionFormPlanVisible = false;
      this.getList();
    },
    getInvList() {
      let query = {};
      this.invList = [];
      // filterAllByUser(query)
      //   .then((response) => {
      //     this.invList = response.data || [];
      //   })
      //   .catch(() => {
      //   });
    },

    newDistributionForm(index, row) {
      this.idQuery.id = '';
      if (this.$isNotBlank(row) && this.$isNotBlank(row.id)) {
        this.idQuery.id = row.id;
        this.idQuery.formData = row;
        this.formName = "update";
      } else
        this.formName = "add";
      this.newSpDistributionVisible = true;
    },

    newDistributionFormPlan(){
      this.formName = "selectPlan";
      this.newDistributionFormPlanVisible = true;
    }

  }
  ,
  components: {
    purContractEdit,purContractSelectPlan,approvalFlowDetail
  }
  ,
  filters: {
    statusFilterType(status) {
      const statusMap = {
        1: "info",
        2: "warning",
        3: "success",
        4: "danger"
      };
      return statusMap[status];
    }
    ,
  }
  ,
  mounted() {
  }
  ,
  created() {
    this.getList();
    this.getInvList();
    this.pageType = this.$route.query.pageType;
  }
  ,
}
;
</script>
<style scoped>
.itemTag {
  float: left;
  text-align: left;
  margin-top: 10px;
  width: 25%;
}

.text {
  font-size: 13px;
  font-family: "Microsoft YaHei";
}


.el-row {
  display: flex;
  flex-wrap: wrap;
}

.el-col {
  border-radius: 4px;
  flex-wrap: wrap;
}
</style>

