<template>
  <div style="padding: 0 20px;">
    <lx-header icon="md-apps" text="合同列表" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
      <div slot="content"></div>
      <slot>
        <div class="selects">
          <div>
            <span style="padding: 0 6px;word-break: keep-all;">创建日期</span>
            <span>
              <DatePicker placeholder="请选择日期" type="daterange" placement="bottom-start" style="width: 200px" @on-change="datePick"></DatePicker>
            </span>
          </div>

          <div>
            <span style="padding: 0 6px;word-break: keep-all;">
            合同类型
            </span>
            <Select placeholder="请选择类型" v-model="select.type" style="width:120px;" clearable>
              <Option v-for="item in [{label:'服务',value:1},{label:'货品',value:2},{label:'工程',value:3}]" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </div>

          <div>
            <span style="padding: 0 6px;word-break: keep-all;">
            科室
          </span>
            <el-cascader
              placeholder="选择科室"
              size="small"
              :value="select.department"
              style="width: 160px;"
              :options="departments"
              :props="{ checkStrictly: true, label: 'name', value: 'id' }"
              clearable
              @change="e => select.department = e[e.length-1] || ''"/>
          </div>

          <div>
            <span style="padding: 0 6px;word-break: keep-all;">
            采购形式
          </span>
            <Select clearable placeholder="请选择采购形式" v-model="select.purchaseModality" style="width:200px;">
              <Option v-for="item in purchaseType" :value="item.id" :key="item.id">{{ item.value }}</Option>
            </Select>
          </div>

          <div>
            <span style="padding: 0 6px;word-break: keep-all;">
            采购方式
          </span>
            <Select clearable placeholder="请选择采购方式" v-model="select.purchaseMethods" style="width:200px;">
              <Option v-for="item in purchaseWay" :value="item.id" :key="item.id">{{ item.value }}</Option>
            </Select>
          </div>

          <div>
            <span style="padding: 0 6px;word-break: keep-all;">
            预算金额
            </span>
            <InputNumber
              placeholder="最小金额"
              :min="0"
              v-model="select.priceMin"
              :formatter="value => `￥${value}`.replace(/B(?=(d{3})+(?!d))/g, ',')"
              :parser="value => value.replace(/$s?|(,*)/g, '')"/>
            <span style="padding: 0 5px;">-</span>
            <InputNumber
              placeholder="最大金额"
              :max="Number.MAX_VALUE"
              v-model="select.priceMax"
              :formatter="value => `￥${value}`.replace(/B(?=(d{3})+(?!d))/g, ',')"
              :parser="value => value.replace(/$s?|(,*)/g, '')"/>
          </div>

          <Button type="primary"  style="margin-left: 10px" @click="isShowAdd = true">新增</Button>
          <Button type="primary"  style="margin-left: 10px" @click="getContracts">查询</Button>
          <Button type="primary"  style="margin-left: 10px" ghost
                  @click=" select = {pageIndex:1,startDate:'',endDate:'',type:'',department:'',purchaseModality:'',purchaseMethods:'',priceMin:null,priceMax:null,status:''}">重置</Button>
          <Button type="primary"  style="margin-left: 10px">导出</Button>
        </div>
      </slot>
    </lx-header>

    <xy-table :table-item="table" :list="list" @editor="" @delete="(row)=>deleteContract(row.id)">
      <template v-slot:btns>
        <el-table-column label="操作" fixed="right" width="200" header-align="center">
          <template slot-scope="scope">
            <div class="slot-btns">
              <Button class="slot-btns-item" type="primary" size="small" @click="$refs['paymentRegistration'].isShowPaymentRegistration = true,$refs['paymentRegistration'].getContract(scope.row)">付款登记</Button>
              <Button class="slot-btns-item" type="primary" size="small" @click="$refs['contractSign'].isShow = true,$refs['contractSign'].contractId = scope.row.id">签订合同</Button>
              <Button class="slot-btns-item" type="primary" size="small" @click="test">招标文件审查</Button>
              <Button class="slot-btns-item" type="primary" size="small">附件管理</Button>
              <Button class="slot-btns-item" type="primary" size="small">请示流程</Button>
              <Button class="slot-btns-item" type="primary" size="small">合同会签流程申请</Button>
              <Button class="slot-btns-item" type="primary" size="small">采购流程申请</Button>
              <Poptip
                placement="bottom"
                :transfer="true"
                confirm
                title="确认要删除吗"
                @on-ok="()=>deleteContract(scope.row.id)">
                <i-button
                  type="error"
                  size="small"
                  ghost>删除</i-button>
              </Poptip>
              <Button class="slot-btns-item" type="primary" size="small" @click="$refs['detailContract'].isShowDetail = true,$refs['detailContract'].getDetail(scope.row.id)">查看</Button>
              <Button class="slot-btns-item" type="primary" size="small" @click="$refs['editor'].isShowEditor = true,$refs['editor'].getDetail(scope.row.id)">编辑</Button>
            </div>
          </template>
        </el-table-column>
      </template>
    </xy-table>

    <div style="display: flex;justify-content: flex-end;">
      <Page :total="total" show-elevator @on-change="pageChange"/>
    </div>

<!--  新增合同  -->
    <xy-dialog :is-show.sync="isShowAdd" title="新增合同" type="form" :form="form" :rules="rules" @submit="submit" ref="addContract">
      <template v-slot:name>
        <Row>
          <Col span="5"><span style="font-weight: 600;padding-right: 4px;color: red;">*</span>项目名称</Col>
          <Col>
            <Input placeholder="请填写项目名称" v-model="form.name" style="width: 300px;"/>
          </Col>
        </Row>
      </template>
      <template v-slot:type>
        <Row>
          <Col span="5"><span style="font-weight: 600;padding-right: 4px;color: red;">*</span>项目类型</Col>
          <Col>
            <Select placeholder="请选择项目类型" v-model="form.type" style="width: 300px;">
              <Option v-for="item in [{label:'服务',value:1},{label:'货品',value:2},{label:'工程',value:3}]" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
        </Row>
      </template>
      <template v-slot:methods>
        <Row>
          <Col span="5"><span style="font-weight: 600;padding-right: 4px;color: red;">*</span>采购类型</Col>
          <Col>
            <Select placeholder="请选择采购类型" v-model="form.methods" style="width: 300px;">
              <Option v-for="item in purchaseType" :value="item.id" :key="item.id">{{ item.value }}</Option>
            </Select>
          </Col>
        </Row>
      </template>
      <template v-slot:modality>
        <Row>
          <Col span="5"><span style="font-weight: 600;padding-right: 4px;color: red;">*</span>采购形式</Col>
          <Col>
            <Select placeholder="请选择采购形式" v-model="form.modality" style="width: 300px;">
              <Option v-for="item in purchaseWay" :value="item.id" :key="item.id">{{ item.value }}</Option>
            </Select>
          </Col>
        </Row>
      </template>
      <template v-slot:price>
        <Row>
          <Col span="5"><span style="font-weight: 600;padding-right: 4px;color: red;">*</span>合同预算价</Col>
          <Col>
            <Input placeholder="请填写合同预算价" v-model="form.price" style="width: 300px;"/>
          </Col>
          <Col offset="1">（万）</Col>
        </Row>
      </template>
      <template v-slot:fundingChannels>
        <Row>
          <Col span="5"><span style="font-weight: 600;padding-right: 4px;color: red;">*</span>资金渠道</Col>
          <Col>
            <Select placeholder="请选择资金渠道" v-model="form.fundingChannels" style="width: 300px;">
              <Option v-for="item in moneyWay" :value="item.id" :key="item.id">{{ item.value }}</Option>
            </Select>
          </Col>
        </Row>
      </template>
      <template v-slot:isBudget>
        <Row>
          <Col span="5"><span style="font-weight: 600;padding-right: 4px;color: red;">*</span>是否预算</Col>
          <Col>
            <i-switch v-model="form.isBudget" @on-change="form.isBudget = $event" />
          </Col>
        </Row>
      </template>
      <template v-if="form.isBudget" v-slot:plan>
        <Row>
          <Col span="5"><span style="font-weight: 600;padding-right: 4px;color: red;">*</span>关联预算计划</Col>
          <Col style="margin: auto 0;">
            <div class="contract-add-plan" style="width: 300px;" @click="isShowPlan = true,getBudgets()">
              <template v-if="form.plan.length > 0">
                <template v-for="item in form.plan">
                  <Tag closable color="primary" @on-close="delPlan(item)">{{item.label}}</Tag>
                </template>
              </template>
              <template v-else>
                <div class="contract-add-plan-no-plan">请选择关联计划</div>
              </template>
            </div>
          </Col>
        </Row>
      </template>
    </xy-dialog>

<!--  新增表 预算计划  -->
    <xy-dialog :is-show.sync="isShowPlan" title="预算计划" :width="640">
      <template v-slot:normalContent>
        <Input v-model="planSearch" search enter-button="搜 索" placeholder="搜索预算计划.." @on-search="getBudgets"/>

        <xy-table :list="plans" :show-index="false" :table-item="planTable" :height="300" style="margin-top: 10px;">
          <template v-slot:btns>
            <el-table-column label="使用金额" header-align="center">
              <template slot-scope="scope">
                <Input :value="scope.row.useMoney ? scope.row.useMoney: scope.row.money" @input="(e)=>scope.row.useMoney = e"/>
              </template>
            </el-table-column>
          </template>
        </xy-table>

        <div style="display: flex;justify-content: flex-end;">
          <Page :total="planTotal" show-elevator @on-change="planPageChange"/>
        </div>
      </template>

      <template v-slot:footerContent>
        <Button type="primary" @click="isShowPlan = false">确定</Button>
      </template>
    </xy-dialog>

<!--    编辑-->
    <editor :is-show-editor.sync="isShowEditor" :purchase-type="purchaseType" :purchase-way="purchaseWay" :money-way="moneyWay" ref="editor" @success="getContracts"></editor>

<!--    查看-->
    <detail ref="detailContract"></detail>

<!--付款登记-->
    <paymentRegistration ref="paymentRegistration"></paymentRegistration>

<!--    合同签订-->
    <contractSign ref="contractSign"></contractSign>
  </div>
</template>

<script>
import {getContract,addContrant,delContract,detailContract,editorContract} from "@/api/contract/contract"
import {getparameter} from "@/api/system/dictionary"
import {listdept} from "@/api/system/department";
import {getBudget} from "@/api/budget/budget"
import {parseTime} from "@/utils"
import {Message} from "element-ui";

import editor from "./components/editorContract"
import detail from "./components/detailContract"
import paymentRegistration from "./components/paymentRegistration";
import contractSign from "@/views/contract/components/contractSign";
export default {
  components:{
    editor,
    detail,
    paymentRegistration,
    contractSign
  },
  data() {
    var planPass = (rule, value, callback) => {
      if(this.form.isBudget){
        if(this.form.plan.length === 0){
          return callback(new Error('必选'))
        }else{
          callback()
        }
      }else{
        callback()
      }
    }
    return {
      //搜索
      select:{
        pageIndex:1,
        startDate:"",
        endDate:"",
        type:"",
        department:"",
        purchaseModality:"",
        purchaseMethods:"",
        priceMin:null,
        priceMax:null,
        status:""
      },
      purchaseType: [],//购买形式
      purchaseWay:[],//购买方式
      moneyWay:[],//资金渠道
      departments:[],//部门科室
      list:[],//数据
      total:0,
      //表格
      table:[
        {
          label:"项目名称",
          width: 160,
          prop:'name'
        },
        {
          label:"采购形式",
          width: 160,
          prop:'purchase_type.value'
        },
        {
          label:"项目类型",
          width: 160,
          prop:'type',
          formatter:(cell,data,value)=>{
            switch (value){
              case 1:
                return "服务"
                break;
              case 2:
                return "货品"
                break;
              case 3:
                return "工程"
                break;
              default:
                return "未知"
            }
          }
        },
        {
          label:"采购方式",
          width: 160,
          prop:"purchase_way.value"
        },
        {
          label:"资金来源",
          width: 160,
          prop:"money_way.value"
        },
        {
          label:"项目预算(万元)",
          width: 200,
          prop:"plan_price",
          align:'right'
        },
        {
          label:"合同状态",
          width: 160,
          prop:"status",
          formatter:(cell,data,value)=>{
            switch (value){
              case 1:
                return "待签订"
                break;
              case 2:
                return "已签订"
                break;
              default:
                return "未知"
            }
          }
        },
        {
          label:"采购流程",
          multiHd:[
            {
              label:"请示流程",
              width: 200
            },
            {
              label:"采购业务审批流程",
              width: 200
            },
            {
              label:"招标审核流程",
              width: 200
            },
            {
              label:"合同会签流程",
              width: 200
            }
          ]
        },
        {
          label:"创建科室",
          width: 200,
          prop:'carry_department'
        },
        {
          label:"创建人",
          width: 200
        },
        {
          label:"创建信息",
          width: 200,
          prop:'created_at',
          formatter:(cell,data,value)=>{
            return parseTime(new Date(value))
          }
        }
      ],

      planTable:[
        {
          sortable:false,
          width:36,
          customFn:(row)=>{
            return (
              <div>
                <Checkbox on={{['on-change']:(e)=>this.selectPlan(e,row)}}></Checkbox>
              </div>
            )
          }
        },
        {
          label:"分类",
          prop:'type',
          formatter:(cell,data,value)=>{
            switch (value){
              case 1:
                return "部门预算"
                break;
              case 2:
                return "水务计划"
                break;
              default:
                return "未知"
            }
          }
        },
        {
          label:"名称",
          prop:'name',
          align:'left'
        },
        {
          label:"计划金额",
          prop:'money',
          align:'right'
        }
      ],


      //新增
      isShowAdd:false,
      form:{
        name:"",
        type:"",
        methods:"",
        modality:"",
        price:"",
        fundingChannels:"",
        isBudget:true,
        plan:[]
      },
      rules:{
        name:[
          {required:true,message:"必填"}
        ],
        type:[
          {required:true,message:"必选"}
        ],
        methods:[
          {required:true,message:"必选"}
        ],
        modality:[
          {required:true,message:"必选"}
        ],
        price:[
          {required:true,message:"必填"}
        ],
        fundingChannels:[
          {required:true,message:"必填"}
        ],
        plan:[
          {validator:planPass}
        ]
      },
      isShowPlan:false,//新增中预算计划
      plans:[],//预算数据
      planSearch:'',
      planTotal:0,
      plansPageIndex:1,

      isShowEditor:false
    }
  },
  methods: {
    test(){
      let win = window.open('https://www.baidu.com', 'baidu', 'top=100,left=100,width=800,height=400')
    },


    //翻页
    pageChange(e){
      this.select.pageIndex = e
      this.getContracts()
    },
    planPageChange(e){
      this.plansPageIndex = e
      this.getBudgets()
    },
    //日期选择
    datePick(e){
      this.select.startDate = e[0]
      this.select.endDate = e[1]
    },

    //获取预算计划
    async getBudgets(){
      let res = await getBudget({name:this.planSearch,page_size:10,page:this.plansPageIndex})
      this.plans = res.data
      this.planTotal = res.total
    },
    //获取资金渠道
    async getMoneyWay(){
      this.moneyWay = (await getparameter({number:'money_way'})).detail
    },
    //获取购买方式
    async getPurchaseWay(){
      this.purchaseWay = (await getparameter({number:'purchase_way'})).detail
    },
    //获取科室
    async getDepartment(){
      this.departments = await listdept()
    },
    //获取购买形式列表
    async getPurchaseType(){
      this.purchaseType = (await getparameter({number:'purchase_type'})).detail
    },

    //获取合同列表
    async getContracts(){
      const res = await getContract({
        page_size:10,
        page:this.select.pageIndex,
        start_created_at:this.select.startDate,
        end_created_at:this.select.endDate,
        type:this.select.type,
        department_id:this.select.department,
        purchase_type_id:this.select.purchaseModality,
        purchase_way_id:this.select.purchaseMethods,
        start_plan_price:this.select.priceMin,
        end_plan_price:this.select.priceMax
      })
      console.log(res)
      this.list = res.data
      this.total = res.total
    },

    //新建合同
    //选择计划
    selectPlan(e,row){
      if(e){
        this.form.plan.push({
          label:row.name,
          value:{
            plan_id:row.id,
            use_money:row.useMoney ?? row.money,
            new_money:row.money
          }
        })
      }else{
        this.form.plan.map((item,index)=>{
          if(item.value.plan_id === row.id){
            this.form.plan.splice(index,1)
          }
        })
      }
    },
    delPlan(val){
      this.form.plan.map((item,index)=>{
        if(item.value.plan_id === val.value.plan_id){
          this.form.plan.splice(index,1)
        }
      })
    },
    //提交新建
    submit(){
      console.log(this.form)
      addContrant({
        type:this.form.type,
        is_plan:this.form.isBudget ? 1 : 0,
        purchase_type_id:this.form.methods,
        purchase_way_id:this.form.modality,
        money_way_id:this.form.fundingChannels,
        plan_price:this.form.price,
        name:this.form.name,
        contract_plan_links:this.form.plan.map(item=>{
          return item.value
        })
      }).then(res=>{
        this.isShowAdd = false
        Message({
          type:'success',
          message:'操作成功'
        })
        this.$refs['addContract'].reset()
        this.getContracts()
      })
    },

    //删除合同
    deleteContract(id){
      delContract({id}).then(res=>{
        Message({
          type:'success',
          message:'操作成功'
        })
        this.getContracts()
      })
    },

  },
  mounted() {
    this.getPurchaseType()
    this.getContracts()
    this.getDepartment()
    this.getPurchaseWay()
    this.getMoneyWay()
  },
}
</script>

<style scoped lang="scss">
  .selects{
    display: flex;
    flex-wrap: wrap;

    &>div{
      margin-bottom: 6px;
    }
  }
  .selectTop{
    margin-top: 10px;
  }

  .contract-add-plan{
    min-height: 30px;
    border: 1px solid #dcdee2;
    border-radius: 4px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    align-content: center;

    padding: 0 8px;
    &-no-plan{
      height: 30px;
      line-height: 30px;
      color: #CDD0D5;
    }
  }



  .slot-btns{
    display: flex;
    flex-wrap: wrap;
    align-content: center;
    justify-content: flex-start;

    &-item{
      margin: 0 6px 4px 0;
    }
  }
</style>
