<template>
  <div>
    <Drawer
      :value="isShow"
      :width="device === 'mobile' ? 100 : 74"
      :title="title||'编辑'"
      :mask-closable="false"
      @input="e => $emit('update:isShow', e)">
      <div style="padding: 20px;">
        <el-form ref="elForm" size="small" :model="form" :rules="rules" label-width="120px">
          <el-form-item prop="name" label="项目名称" required :class="device === 'desktop' ? 'span2' : ''">
            <el-input
              placeholder="请填写项目名称"
              v-model="form.name"
              style="width: 100%"
            />
          </el-form-item>

          <template v-if="!isLedger">
            <el-form-item v-if="!isOtherFlow" prop="is_simple" label="是否为直接支付" :class="device === 'desktop' ? 'span2' : ''">
              <el-switch
                v-model="form.is_simple"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              />
              <span style="flex: 1; text-align: right">（无需采购流程，如水电邮寄费等）</span>
            </el-form-item>

            <el-form-item prop="flow_mod_id" label="事前流程" v-if="!form.is_simple">
              <template v-if="!form.is_common_purchase">
                <el-select v-model="form.flow_mod_id" style="width: 100%">
                  <el-option v-for="item in flowIdsFormat" :key="item.id" :value="item.id" :label="item.name"></el-option>
                </el-select>
              </template>
              <template v-else>
                <el-input
                  readonly
                  placeholder="请填写项目名称"
                  value="一般采购"
                  style="width: 100%"
                />
              </template>
            </el-form-item>

            <el-form-item v-if="!isOtherFlow" prop="is_contract" label="是否需要签订合同">
              <el-switch
                v-model="form.is_contract"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>

            <el-form-item v-if="!isOtherFlow" prop="is_trade" label="是否为工会项目">
              <el-switch
                v-model="form.is_trade"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>

            <el-form-item prop="money_way_id" label="资金渠道">
              <el-select
                multiple
                size="small"
                clearable
                placeholder="请选择资金渠道"
                :value="
                  form.money_way_id
                    ? form.money_way_id.split(',').map((i) => Number(i))
                    : []
                "
                style="width: 100%"
                @change="
                  (e) => {
                    form.money_way_id = e.length > 0 ? e.toString() : '';
                  }
                "
              >
                <el-option
                  v-for="item in moneyWay"
                  :value="item.id"
                  :label="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <template v-if="form.is_simple">
              <el-form-item prop="supply" label="承包商/供货商">
                <el-input
                  v-model="form.supply"
                  placeholder="请填写承包商/供货商"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item prop="money" label="金额（元）">
                <InputNumber
                  style="width: 100%"
                  :min="0"
                  :step="10000"
                  :precision="2"
                  :active-change="false"
                  :value="Number(form.money)"
                  @input="e => form.money = e"
                  :formatter="
                  (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                "
                  :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                ></InputNumber>
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item prop="type" label="项目类型" v-if="isNeedMore">
                <el-select
                  clearable
                  placeholder="请选择项目类型"
                  v-model="form.type"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in types"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="purchase_type_id" label="采购形式" v-if="isNeedMore">
                <el-select
                  ref="purchaseTypeInput"
                  clearable
                  placeholder="请选择采购形式"
                  v-model="form.purchase_type_id"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in purchaseType"
                    :label="item.value"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="purchase_way_id" label="采购方式" v-if="isNeedMore">
                <el-select
                  clearable
                  placeholder="请选择采购方式"
                  v-model="form.purchase_way_id"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in purchaseWay"
                    :label="item.value"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="group_type" label="组织形式" v-if="isNeedMore">
                <el-select
                  clearable
                  placeholder="请选择组织形式"
                  v-model="form.group_type"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in groupType"
                    :label="item.value"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="plan_price" label="预算价（元）">
                <InputNumber
                  style="width: 100%"
                  :min="0"
                  :step="10000"
                  :precision="2"
                  :active-change="false"
                  :value="Number(form.plan_price)"
                  :formatter="
                  (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                "
                  :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                  @input="e => form.plan_price = e"
                ></InputNumber>
              </el-form-item>

              <el-form-item label="流程状态" v-if="userList.indexOf($store.state.user.username) !== -1" :class="device === 'desktop' ? 'span2' : ''">
                <div>
                  <el-button size="small" type="primary" icon="el-icon-plus" @click="form.flow_list.push({flow_id: '',flow_status: '',custom_model_id: '',flow_title: ''})">新增记录</el-button>

                  <xy-table :list="form.flow_list"
                            style="width: 100%;margin-top: 10px;"
                            :show-index="false"
                            :height="400"
                            :table-item="statusTable">
                    <template #btns></template>
                  </xy-table>
                </div>
              </el-form-item>

              <el-form-item prop="contract_plan_links"
                            label="关联预算计划"
                            v-if="!form.is_common_purchase">
                <div class="plan-pick"
                     style="width: 100%;"
                     @click="isShowPlan = true,getPlan()">
                  <template v-if="form.contract_plan_links instanceof Array && form.contract_plan_links.length > 0">
                    <template v-for="item in form.contract_plan_links">
                      <el-tag
                        effect="dark"
                        size="mini"
                        closable
                        color="primary"
                        @close="_ => {
                          let findIndex = form.contract_plan_links.findIndex(j => j.id === item.id)
                          if (findIndex !== -1) {
                            form.contract_plan_links.splice(findIndex, 1)
                          }
                        }">{{ item.label }}</el-tag>
                    </template>
                  </template>
                  <template v-else>
                    <div class="plan-pick-none">请选择关联计划</div>
                  </template>
                </div>
              </el-form-item>
            </template>

            <el-form-item
              v-if="!isOtherFlow"
              prop="use_framework_buy"
              label="是否使用框架协议采购内容"
            >
              <el-switch
                v-model="form.use_framework_buy"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
            <el-form-item
              v-if="!isOtherFlow"
              prop="is_framework"
              label="是否新生成框架协议"
              v-show="isShowIsFramework"
            >
              <el-switch
                v-model="form.is_framework"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
            <el-form-item
              prop="contract_to_contracts"
              label="关联的框架协议合同"
              v-show="form.use_framework_buy"
            >
              <div class="plan-pick" style="width: 100%;" @click="isShowContractToContracts = true">
                <template v-if="selections.length > 0">
                  <template v-for="item in selections">
                    <el-tag effect="dark"
                            size="mini"
                            closable
                            color="primary"
                            @close="delSelections(item)">{{ item.name }}</el-tag>
                  </template>
                </template>
                <template v-else>
                  <div class="plan-pick-none">请选择关联的框架协议合同</div>
                </template>
              </div>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item prop="is_contract" label="是否需要签订合同">
              <el-switch
                disabled
                :value="true"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>

            <el-form-item prop="contract_type" label="是否需要签订合同">
              <el-select style="width: 100%" v-model="form.contract_type">
                <el-option v-for="(item,index) in contractTypes" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="supply" label="承包商\供应商">
              <el-input style="width: 100%;" placeholder="请填写承包商\供应商" v-model="form.supply" />
            </el-form-item>

            <el-form-item prop="money" label="金额（元）">
              <InputNumber
                style="width: 100%"
                :min="0"
                :step="10000"
                :precision="2"
                :active-change="false"
                v-model="form.money"
                :formatter="
                  (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                "
                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
              ></InputNumber>
            </el-form-item>

            <el-form-item
              prop="is_framework"
              label="是否新生成框架协议"
              v-show="isShowIsFramework"
            >
              <el-switch
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>

            <el-form-item
              prop="contract_to_contracts"
              label="关联的框架协议合同"
              v-show="form.use_framework_buy"
            >
              <div class="plan-pick" style="width: 100%;" @click="isShowContractToContracts = true">
                <template v-if="selections.length > 0">
                  <template v-for="item in selections">
                    <el-tag effect="dark"
                            size="mini"
                            closable
                            color="primary"
                            @close="delSelections(item)">{{ item.name }}</el-tag>
                  </template>
                </template>
                <template v-else>
                  <div class="plan-pick-none">请选择关联的框架协议合同</div>
                </template>
              </div>
            </el-form-item>
          </template>

          <el-form-item class="span2">
            <div style="display: flex;align-items: center;justify-content: center;">
              <el-button type="primary" plain style="width: 100px;" @click="reset">重置</el-button>
              <el-button type="primary" style="width: 100px; margin-left: 40px;" @click="submit">确认</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </Drawer>

    <!--  编辑中 预算计划  -->
    <xy-dialog :is-show.sync="isShowPlan"
               title="预算计划"
               :width="820">
      <template>
        <div style="display: flex;align-items: center;">
          <DatePicker
            :value="planSelect.year"
            placeholder="选择所属年份"
            placement="bottom-start"
            style="width: 140px;margin-right: 10px;"
            type="year"
            @on-change="(e) => {
              planSelect.year = e
              getPlan()
            }"
          ></DatePicker>
          <el-select
            placeholder="科室选择"
            clearable
            size="small"
            v-model="planSelect.plan_department_id"
            style="width: 180px;margin-right: 10px;"
            @change="getPlan"
          >
            <el-option
              v-for="item in departments"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
          </el-select>
          <Input v-model="planSelect.name"
                 search
                 enter-button="搜 索"
                 placeholder="搜索预算计划.."
                 @on-search="getPlan" />
        </div>

        <xy-table :list="plans"
                  :show-index="false"
                  :table-item="planTable"
                  :height="310"
                  style="margin-top: 10px;"
                  ref="PlanTable"
                  row-key="id"
                  border
                  default-expand-all
                  :tree-props="{ children: 'notChildren', hasChildren: 'hasChildren' }"
                  @selection-change="planPick">
          <template v-slot:btns>
            <el-table-column label="使用金额（元）" header-align="center" width="150" fixed="right">
              <template slot-scope="scope" v-if="scope.row.pid === 0">
                <InputNumber
                  style="width: 120px"
                  :min="0"
                  :precision="2"
                  :active-change="false"
                  :value="Number(scope.row._inputMoney)"
                  @input="e => scope.row._inputMoney = e"
                  :formatter="
                    (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                  "
                  :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                ></InputNumber>
              </template>
            </el-table-column>
          </template>
        </xy-table>
      </template>

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

    <!--    新增表 框架合同-->
    <xy-dialog title="框架协议" :is-show.sync="isShowContractToContracts" :width="820">
      <Table
        :data="contractList"
        :columns="contractTable"
        :loading="loading"
        border
        size="small"
        @on-selection-change="selectionChange"
      ></Table>
      <div style="display: flex; justify-content: center; margin: 10px 0">
        <Page :total="contractTotal"
              size="small"
              show-elevator
              show-total
              @on-change="e => {
                contractSelect.page = e;
                getContractToContracts();
              }"/>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowContractToContracts = false">取 消</el-button>
        <el-button type="primary" @click="isShowContractToContracts = false">确 定</el-button>
      </span>
    </xy-dialog>
  </div>
</template>

<script>
import {checkContractName, detailContract, editorContract, getContract} from '@/api/contract/contract'
import { getparameter, getparameterTree } from "@/api/system/dictionary";
import { deepCopy } from "@/utils";
import { getBudget } from "@/api/budget/budget";
import { flowStatusConfig } from "@/api/common";
export default {
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    flowIds: {
      type: Array,
      default: () => []
    },
    groupType: {
      type: Array,
      default: () => []
    },
    purchaseType: {
      type: Array,
      default: () => []
    },
    moneyWay: {
      type: Array,
      default: () => []
    },
    purchaseWay: {
      type: Array,
      default: () => []
    },
    commonPurchaseType: {
      type: Array,
      default: () => []
    },
    types: {
      type: Array,
      default: () => []
    },
    departments: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // flow_list
      userList: ['admin','xiaoyi'],
      flowConfig: [],
      flowStatus: new Map([
        [2, "待申请"],
        [-1, "已退回"],
        [-2, "-"],
        [0, "流转中"],
        [1, "已办结"]
      ]),
      statusTable: [
        {
          prop: 'flow_id',
          label: '流程id',
          customFn: (row) => {
            return (
              <el-input size="small" vModel={row.flow_id}></el-input>
            )
          }
        },
        {
          prop: 'flow_status',
          label: '状态',
          customFn: (row) => {
            return (
              <el-select size="small" vModel={row.flow_status} placeholder="请选择">
                {
                  Array.from(this.flowStatus).map(item => (
                    <el-option label={item[1]} value={item[0]}></el-option>
                  ))
                }
              </el-select>
            )
          }
        },
        {
          prop: 'custom_model_id',
          label: '流程',
          customFn: (row) => {
            return (
              <el-select size="small" vModel={row.custom_model_id} placeholder="请选择">
                {
                  this.flowIds.map(item => (
                    <el-option label={item.name} value={item.id}></el-option>
                  ))
                }
              </el-select>
            )
          }
        },
        {
          prop: 'flow_title',
          label: '标题',
          customFn: (row) => {
            return (
              <el-input size="small" vModel={row.flow_title}></el-input>
            )
          }
        }
      ],
      //
      // contract_to_contracts
      selections: [],
      contractSelect: {
        page: 1,
        page_size: 10,
        is_framework: 1
      },
      contractList: [],
      loading: false,
      contractTable: [
        {
          type: "selection",
          width: 56,
          align: "center",
        },
        {
          title: "项目名称",
          key: "name",
          minWidth: 180,
          align: "left",
        },
        {
          title: "采购形势",
          width: 120,
          render: (h,{row}) => {
            return h('span',{},row.purchase_type?.value || "无")
          }
        },
        {
          title: "项目类型",
          width: 120,
          render: (h,{row}) => {
            let map = new Map([
              [1,"服务"],
              [2,"货物"],
              [3,"工程"]
            ])
            return h('span',{},map.get(row.type))
          }
        },
        {
          title: "采购方式",
          width: 120,
          render: (h,{row}) => {
            return h('span',{},row.purchase_way?.value || "无")
          }
        }
      ],
      contractTotal: 0,
      isShowContractToContracts: false,
      //
      // plan
      isShowPlan: false,
      plans: [],
      planSelect: {
        name: "",
        page_size: 20,
        page: 1,
        is_tree: 1,
        year: new Date().getFullYear().toString(),
        plan_department_id: "",
        type: ""
      },
      planTable: [{
        fixed: 'left',
        sortable: false,
        width: 44,
        reserveSelection: true,
        type: "selection",
        selectable: (row, index) => {
          return row.pid === 0
        },
      },
        {
          label: "科室",
          prop: 'plan_department.name',
          width: 160,
          align: 'center'
        },
        {
          label: "年份",
          prop: 'year',
          width: 80,
          align: 'center'
        },
        {
          label: "分类",
          prop: 'type_detail.value',
        },
        {
          label: "名称",
          prop: 'name',
          align: 'left',
          width: 220,
        },
        {
          label: "计划金额",
          prop: 'money',
          align: 'right',
          width: 120,
        },
        {
          label: "实付金额",
          prop: 'use_money_total',
          width: 120,
          align: 'right'
        },
        {
          label: '已用金额',
          prop: 'has_money_total',
          width: 120,
          align: 'right'
        }
      ],
      planTotal: 0,
      //
      title: "编辑",
      form: {
        id: "",
        type: "",
        is_plan: 1,
        purchase_type_id: "",
        flow_mod_id: "",
        is_contract: 1,
        purchase_way_id: "",
        money_way_id: "",
        group_type: "",
        plan_price: 0,
        name: "",
        contract_plan_links: [],
        is_simple: 0,
        supply: "",
        money: 0,
        status: 1,
        is_framework: 0,
        use_framework_buy: 0,
        content: "",
        contract_to_contracts: [],
        outcome_type: 1,
        is_purchase: 1,
        is_trade: 0,
        remark: '',
        is_common_purchase: 0,
        common_type: '',
        flow_list: []
      },
      rules: {
        name: [
          {
            required: true,
            message: "必填",
            trigger: "blur",
          },
          {
            validator: async (rule, value, callback) => {
              if (!this.hasValue(value)) {
                callback(new Error("必填"));
              } else {
                if (value === this.title) {
                  callback()
                  return
                }
                const res = await checkContractName({ name: value });
                if (res === "未重名" || value === this.title) {
                  callback();
                } else {
                  callback(new Error("名称重名"));
                }
              }
            },
            trigger: "blur",
          },
        ],
        supply: [
          {
            validator: (rule, value, callback) => {
              if (this.form.is_simple) {
                if (!this.hasValue(value)) {
                  callback(new Error("必填"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        type: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.is_simple || !this.isNeedMore || !this.form.is_common_purchase) {
                if (!this.hasValue(value)) {
                  callback(new Error("必填"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        purchase_type_id: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.is_simple || !this.isNeedMore || !this.form.is_common_purchase) {
                if (!this.hasValue(value)) {
                  callback(new Error("必填"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        purchase_way_id: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.is_simple || !this.isNeedMore || !this.form.is_common_purchase) {
                if (!this.hasValue(value)) {
                  callback(new Error("必填"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        money: [
          {
            validator: (rule, value, callback) => {
              if (this.form.is_simple) {
                if (!this.hasValue(value)) {
                  callback(new Error("必填"));
                } else {
                  if (/^\d+(\.\d+)?$/.test(value)) {
                    callback();
                  } else {
                    callback(new Error("必须为数字"));
                  }
                }
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        plan_money: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.is_simple || !this.form.is_common_purchase) {
                if (!this.hasValue(value)) {
                  callback(new Error("必填"));
                } else {
                  if (/^\d+(\.\d+)?$/.test(value)) {
                    callback();
                  } else {
                    callback(new Error("必须为数字"));
                  }
                }
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        money_way_id: [
          {
            validator: (rule, value, callback) => {
              if (!this.hasValue(value) || !this.form.is_common_purchase) {
                callback(new Error("必填"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        contract_plan_links: [
          {
            validator: (rule, value, callback) => {
              if (this.form.is_plan) {
                if (this.form.contract_plan_links.length === 0) {
                  return callback(new Error("必选"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        contract_to_contracts: [
          {
            validator: (rule, value, callback) => {
              if (this.form.use_framework_buy) {
                if (this.form.contract_to_contracts.length === 0) {
                  return callback(new Error("必选"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
      contractTypes: [
        { label: "收入类", value: 1 },
        { label: "支出类", value: 2 },
        { label: "技术协议", value: 3 },
      ],
    }
  },
  methods: {
    hasValue(value) {
      return (
        value !== "" &&
        value !== undefined &&
        value !== "undefined" &&
        value !== null
      );
    },
    planPick(selection) {
      this.form.contract_plan_links = selection.map(i => ({
        id: i._linkId,
        label: i.name,
        plan_id: i.id,
        use_money: i._inputMoney,
        new_money: i.money
      }))
    },
    async getDetail(id) {
      try {
        const res = await detailContract({ id })
        for (let key in this.form) {
          if (res.hasOwnProperty(key)) {
            this.form[key] = res[key]
          }
        }
        this.title = res.name
        this.form.contract_plan_links = res.plan_link.map(link => {
          let myPlan = res.plans.find(j => j.id === link.plan_id)
          if (myPlan) {
            return {
              id: link.id,
              label: myPlan.name,
              plan_id: link.plan_id,
              use_money: link.use_money,
              new_money: myPlan.money
            }
          } else {
            return false
          }
        }).filter(i => !!i)

        setTimeout(() => {
          this.copyForm = deepCopy(this.form)
        }, 500)
      } catch (err) {
        console.error(err)
      }
    },
    async getFlowConfig() {
      try {
        const res = await flowStatusConfig()
        this.flowConfig = res.map(i => JSON.parse(i.value))
      } catch (err) {
        this.flowConfig = []
      }
    },
    async getPlan() {
      try {
        let res = await getBudget(this.planSelect)
        let copyPlan = deepCopy(this.form.contract_plan_links)
        this.$refs['PlanTable'].clearSelection()
        res.list.forEach((item) => {
          let temp = copyPlan.find(i => i.plan_id === item.id)
          if (temp) {
            item._linkId = temp.id
            item._inputMoney = temp.use_money
            this.$nextTick(() => {
              this.$refs['PlanTable'].toggleRowSelection(item, true)
            })
          } else {
            item._inputMoney = 0
          }
        });
        this.plans = res.list;
        this.planTotal = res.list.total ?? 0;
      } catch (e) {

      }
    },


    //框架合同
    async getContractToContracts() {
      const res = await getContract(this.contractSelect)
      let selectedIds = this.selections.map(i => i.id)
      this.contractList = res.list.data.map(item => {
        return {
          ...item,
          _checked: !!selectedIds.find(i => i === item.id),
        }
      })
      this.contractTotal = res.list.total
    },
    selectionChange(selection) {
      this.selections = Array.from(
        new Set(
          selection
        )
      );
    },
    delSelections(val) {
      this.selections.map((item, index) => {
        if (item.id === val.id) {
          this.selections.splice(index, 1)
        }
      })
    },

    reset() {
      this.form = this.copyForm
    },
    submit() {
      this.$refs['elForm'].validate().then(_ => {
        this.form.contract_to_contracts = this.selections.map(i => {
          return {
            contract_id: this.contrantId,
            to_contract_id: i.id,
            use_money: i.money
          }
        })
        this.form.contract_flow_links = this.form.flow_list.map(i => ({
          ...i,
          tag: this.flowConfig.find(j => j.custom_model_id == i.custom_model_id)?.tag
        }))
        editorContract(this.form).then(_ => {
          this.$message.success('修改成功')
          this.$emit('update:isShow', false)
          this.$emit('refresh')
        })
      })
    }
  },
  computed: {
    device() {
      return this.$store.state.app.device
    },
    isLedger () {
      return this.$route.query.isLedger;
    },
    isShowIsFramework() {
      let temp1 = this.form.purchase_type_id;
      let temp2 = this.form.use_framework_buy;
      if (
        this.$refs["purchaseTypeInput"]?.selected?.label === "直接采购" &&
        this.form.use_framework_buy
      ) {
        this.form.is_framework = true;
        return false;
      } else {
        return true;
      }
    },
    contractToContractsSelections () {
      let temp = this.form.contract_to_contracts;
      return this.$refs["contractToContractsTable"]?.getSelection() || []
    },
    flowIdsFormat () {
      let temp = this.form.is_trade;
      return temp ? this.flowIds?.filter(i => /工会/g.test(i.name))  : this.flowIds
    },

    isOtherFlow () {
      return this.flowIds?.find(i => i.id === this.form.flow_mod_id)?.type == 1;
    },
    isNeedMore () {
      //是否需要组织形式等
      return this.flowIds?.find(i => i.id === this.form.flow_mod_id)?.name === "政府采购流转" || this.flowIds?.find(i => i.id === this.form.flow_mod_id)?.name === "政府小额采购"
    },
    purchaseWayFormat() {
      return function () {
        if (!this.form.purchase_type_id) {
          return this.purchaseWay;
        } else {
          let temp = this.purchaseType.find((i) => i.id === this.form.purchase_type_id);
          let arr = temp?.remark?.split(",")?.map((i) => Number(i));
          return this.purchaseWay.filter((i) => arr.indexOf(i.id) !== -1);
        }
      };
    },
    created() {
      this.getFlowConfig()
    }
  },
}
</script>

<style scoped lang="scss">
.plan-pick {
  min-height: 30px;
  border: 1px solid #dcdee2;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  align-content: center;

  padding: 0 8px;
  ::v-deep .el-tag {
    margin: 2px;
  }
  &-none {
    height: 30px;
    line-height: 30px;
    color: #CDD0D5;
  }
}
::v-deep .el-form {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 0 10px;
}
.span2 {
  grid-column: span 2;
}
@media (max-width: 768px) {
  ::v-deep .el-form {
    display: grid;
    grid-template-columns: repeat(1, 1fr);
    grid-gap: 0;
  }
}
</style>
