<template>
  <div>
    <xy-dialog
      ref="dialog"
      :is-show.sync="isShow"
      type="form"
      :title="type === 'add' ? '新增政府采购计划' : '编辑政府采购计划'"
      :form="form"
      :rules="rules"
      @submit="submit"
    >
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >
            项目名称 ：
          </div>
          <div class="xy-table-item-content">
            <el-input
              :readonly="role === 1"
              v-model="form.name"
              clearable
              placeholder="请输入项目名称"
              style="width: 300px"
            ></el-input>
          </div>
        </div>
      </template>
      <template v-slot:content>
        <div class="xy-table-item">
          <div class="xy-table-item-label">项目内容 ：</div>
          <div class="xy-table-item-content">
            <el-input
              :readonly="role === 1"
              type="textarea"
              :autosize="{ minRows: 2 }"
              v-model="form.content"
              clearable
              placeholder="请输入项目内容"
              style="width: 300px"
            ></el-input>
          </div>
        </div>
      </template>
      <template v-slot:plan_money>
        <div class="xy-table-item">
          <div class="xy-table-item-label">采购预算 ：</div>
          <div class="xy-table-item-content xy-table-item-price">
            <el-input-number
              :disabled="role === 1"
              v-model="form.plan_money"
              clearable
              placeholder="请输入采购预算"
              style="width: 300px"
              :controls="false"
            ></el-input-number>
          </div>
        </div>
      </template>
      <template v-slot:public_plane_date v-if="role == 0">
        <div class="xy-table-item">
          <div class="xy-table-item-label">采购意向公开计划时间 ：</div>
          <div class="xy-table-item-content">
            <el-date-picker
              v-model="form.public_plane_date"
              placeholder="请选择采购意向公开计划时间"
              style="width: 300px"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:public_act_date v-if="role == 1">
        <div class="xy-table-item">
          <div class="xy-table-item-label">采购意向公开实际时间 ：</div>
          <div class="xy-table-item-content">
            <el-date-picker
              v-model="form.public_act_date"
              placeholder="请选择采购意向公开实际时间"
              style="width: 300px"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:invite_plane_date v-if="role == 0">
        <div class="xy-table-item">
          <div class="xy-table-item-label">招标文件挂网计划时间 ：</div>
          <div class="xy-table-item-content">
            <el-date-picker
              v-model="form.invite_plane_date"
              placeholder="请选择招标文件挂网计划时间"
              style="width: 300px"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:invite_act_date v-if="role == 1">
        <div class="xy-table-item">
          <div class="xy-table-item-label">招标文件挂网实际时间 ：</div>
          <div class="xy-table-item-content">
            <el-date-picker
              v-model="form.invite_act_date"
              placeholder="请选择招标文件挂网实际时间"
              style="width: 300px"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:open_plane_date v-if="role == 0">
        <div class="xy-table-item">
          <div class="xy-table-item-label">项目开标计划时间 ：</div>
          <div class="xy-table-item-content">
            <el-date-picker
              v-model="form.open_plane_date"
              placeholder="请选择项目开标计划时间"
              style="width: 300px"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:open_act_date v-if="role == 1">
        <div class="xy-table-item">
          <div class="xy-table-item-label">项目开标实际时间 ：</div>
          <div class="xy-table-item-content">
            <el-date-picker
              v-model="form.open_act_date"
              placeholder="请选择项目开标实际时间"
              style="width: 300px"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </div>
      </template>
      <template #plan_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            关联预算计划
          </div>
          <div class="xy-table-item-content">
            <div
              class="contract-add-plan"
              style="width: 300px"
              @click="isShowPlan = true"
            >
              <template>
                <el-input
                  readonly
                  :value="form.plan ? form.plan.name : form.plan_id"
                  clearable
                  placeholder="请选择关联计划"
                  style="width: 300px"
                  @focus="isShowPlan = true"
                ></el-input>
              </template>
            </div>
          </div>
        </div>
      </template>
    </xy-dialog>


    <!--  新增表 预算计划  -->
    <xy-dialog
      :is-show.sync="isShowPlan"
      :width="720"
      title="预算计划"
      @on-ok="isShowPlan = false"
    >
      <template v-slot:normalContent>
        <div style="display: flex">
          <el-select
            placeholder="科室选择"
            clearable
            size="small"
            v-model="planSearch.plan_department_id"
            style="width: 160px"
          >
            <el-option
              v-for="item in departments"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
          </el-select>
          <Input
            v-model="planSearch.name"
            enter-button="搜 索"
            placeholder="搜索预算计划.."
            search
            @on-search="searchBudgets"
          />
        </div>
        <xy-table
          highlight-current-row
          ref="planTable"
          :height="300"
          :list="plans"
          :show-index="false"
          :table-item="planTable"
          style="margin-top: 10px"
          @cellClick="row => { form.plan_id = row.id;form.plan = row; }"
        >
          <template #btns>
          </template>
        </xy-table>

        <div style="display: flex; justify-content: flex-end">
          <Page :total="planTotal" show-elevator @on-change="e => { planSearch.page = e;getBudgets(); }" />
        </div>
      </template>

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

<script>
import { show, save, store } from "@/api/govPlane";
import {getBudget} from "@/api/budget/budget";
import {listdeptNoAuth} from "@/api/system/department";
import {getparameter} from "@/api/system/dictionary";
export default {
  props: {
    role: Number
  },
  data() {
    return {
      isShowPlan: false,
      departments: [],
      moneyWay: [],
      planTotal: 0,
      plans: [],
      planSearch: {
        name: "",
        plan_department_id: "",
        page: 1,
        page_size: 10,
        top_pid: 1
      },
      planTable: [
        {
          label: "分类",
          prop: "type",
          formatter: (cell, data, value) => {
            let res = this.moneyWay.filter((item) => {
              return item.id === value;
            });
            return res[0]?.value || "未知";
          },
          width: 100,
          fixed: "left",
        },

        {
          label: "科室",
          prop: "plan_department.name",
          width: 100,
          align: "center",
        },
        {
          label: "年份",
          prop: "year",
          width: 80,
          align: "center",
        },
        {
          label: "隶属",
          prop: "pid_info.name",
          width: 180,
          align: "left",
        },
        {
          label: "名称",
          prop: "name",
          width: 320,
          align: "left",
        },
        {
          label: "计划金额",
          prop: "money",
          align: "right",
          width: 120,
          customFn: (row) => {
            let m1 = row.money;
            let m2 = row.update_money;

            return m2 == 0 ? m1 : m2;
          },
        },
        {
          label: "已用金额",
          prop: "use_money_total",
          width: 120,
          align: "right",
        },
      ],


      isShow: false,
      id: "",
      type: "",

      form: {
        name: "",
        content: "",
        plan_money: "",
        public_plane_date: "",
        public_act_date: "",
        invite_plane_date: "",
        invite_act_date: "",
        open_plane_date: "",
        open_act_date: "",
        plan_id: "",
        plan: {}
      },
      rules: {
        name: [
          {
            required: true,
            message: "请填写项目名称",
          },
        ],
      },
    };
  },
  methods: {
    show() {
      this.isShow = true;
    },
    hidden() {
      this.isShow = false;
    },
    init() {
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$refs["dialog"].clearValidate();
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },
    getId() {
      return this.id;
    },
    setType(type = "add") {
      let types = ["add", "editor"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type);
      }
    },
    setForm(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this.form[key] = value[index] ?? "";
        });
      }
      if (typeof key === "string") {
        this.form[key] = value;
      }
      if (!key) {
        this.init();
      }
    },

    async getDetail() {
      const res = await show({ id: this.id });
      this.$integrateData(this.form, res);
    },

    submit() {
      if (this.type === "add") {
        if (this.form.hasOwnProperty("id")) {
          delete this.form.id;
        }
        store(this.form).then((res) => {
          this.$message({
            type: "success",
            message:
              this.type === "add"
                ? "新增政府采购计划"
                : "编辑政府采购计划" + "成功",
          });
          this.isShow = false;
          this.$emit("refresh");
        });
      }
      if (this.type === "editor") {
        Object.defineProperty(this.form, "id", {
          value: this.id,
          enumerable: true,
          configurable: true,
          writable: true,
        });
        save(this.form).then((res) => {
          this.$message({
            type: "success",
            message:
              this.type === "add"
                ? "新增政府采购计划"
                : "编辑政府采购计划" + "成功",
          });
          this.isShow = false;
          this.$emit("refresh");
        });
      }
    },

//获取科室
    async getDepartment() {
      this.departments = await listdeptNoAuth();
    },
    //获取资金渠道
    async getMoneyWay() {
      this.moneyWay = (
        await getparameter({
          number: "money_way",
        })
      ).detail;
    },

    //确认计划选择
    planSelect(row) {
      console.log(row)
      // if (this.plan.length === 0) {
      //   this.$message({
      //     type: "warning",
      //     message: "选择计划不能为空",
      //   });
      //   return;
      // }
      //
      // this.isShowPlan = false;
    },
    searchBudgets() {
      this.getBudgets();
    },
    //获取预算计划
    async getBudgets() {
      let res = await getBudget(this.planSearch);
      this.plans = res.list.data;

      this.planTotal = res.list.total;
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        if (this.type === "editor") {
          this.getDetail();
        }
      } else {
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["dialog"].clearValidate();
        delete this.form.id;
      }
    },
    isShowPlan(val) {
      if (val) {
        this.$refs['planTable'].setCurrentRow(this.plans.find(row => row.id === this.form.plan_id))
      }
    }
  },
  created() {
    this.getMoneyWay();
    this.getDepartment();
    this.getBudgets();
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  text-align: left;
}
.xy-table-item-label {
  width: 200px;
}
.xy-table-item-price {
  position: relative;

  &::after {
    z-index: 1;
    position: absolute;
    right: 0;
    top: 0;
    content: '（元）'
  }

  ::v-deep .el-input__clear {
    position: relative;
    right: 30px;
    z-index: 2;
  }
}
</style>
