<template>
  <div>
    <xy-dialog
      ref="dialog"
      :is-show.sync="isShow"
      type="form"
      :title="type === 'add' ? '新增财评评审' : '编辑财评评审'"
      :form="form"
      :rules="rules"
      @submit="submit"
    >
      <template #pid>
        <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-cascader
              :options="[{children:lists,project_name:'总包项目',id:0}]"
              :props="{ checkStrictly: true, label: 'project_name', value: 'id' }"
              :value="form.pid"
              clearable
              style="width: 300px"
              @change="(e) => {
                form.pid = e.at(-1)
              }"
            />
          </div>
        </div>
      </template>
      <template v-slot:project_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
              :disabled="type === 'editor'"
              v-model="form.project_name"
              placeholder="请输入项目"
              style="width: 300px"
            >
              <el-button
                icon="el-icon-arrow-right"
                type="primary"
                slot="suffix"
                @click="isShowModal = true">
              </el-button>
            </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-select
              v-model="form.content"
              clearable
              placeholder="请选择评审内容"
              style="width: 300px"
            >
              <el-option v-for="i in ['概算评审','预算评审','竣工结算评审','竣工财务评审']" :label="i" :value="i">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:plan_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
              type="month"
              v-model="form.plan_date"
              placeholder="请选择计划评审时间"
              style="width: 300px"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:actually_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.actually_date"
              placeholder="请选择实际评审时间"
              style="width: 300px"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </div>
      </template>

      <template #item_list>
        <el-button
          v-if="role == 0"
          icon="el-icon-plus"
          type="primary"
          size="small"
          @click="
            form.item_list.push({
              content: '',
              plan_date: '',
              actually_date: '',
              date: ''
            })
          "
          >新增</el-button
        >
        <xy-table
          style="margin-top: 20px"
          :height="320"
          :table-item="itemTable"
          :list="form.item_list"
        >
          <template #btns> </template>
        </xy-table>
      </template>
    </xy-dialog>

    <Modal title="项目" v-model="isShowModal" :width="50" @on-ok="rowPick(tempRow)" @on-visible-change="t => t ? '' : (tempRow = {},$refs['budgetTable'].clearCurrentRow())">
      <div class="select">
        <DatePicker
          :value="budgetSelect.year"
          placeholder="选择所属年份"
          placement="bottom"
          style="width: 130px"
          type="year"
          @on-change="(e) => (budgetSelect.year = e)"
        ></DatePicker>


        <Select
          placeholder="科室选择"
          clearable
          v-model="budgetSelect.department_id"
          style="width: 160px"
        >
          <Option
            v-for="item in departments"
            :value="item.id"
            :key="item.id"
          >{{item.name}}
          </Option>
        </Select>

        <Input v-model="budgetSelect.keyword" placeholder="关键词" clearable style="width: 160px"></Input>

        <Button style="float: right;" type="primary" @click="budgetSelect.page=1,getContract()"
        >查询</Button
        >
      </div>

      <Table
        ref="budgetTable"
        :height="440"
        :data="budgets"
        :columns="budgetTable"
        highlight-row
        @on-row-click="row => tempRow = row"
      ></Table>

      <div style="padding: 10px 0; display: flex; justify-content: center">
        <Page
          :page-size="20"
          :total="budgetTotal"
          show-elevator
          @on-change="
            (e) => {
              budgetSelect.page = e;
              getContract();
            }
          "
        />
      </div>
    </Modal>
  </div>
</template>

<script>
import { getContract } from "@/api/contract/contract"
import { getBudget } from "@/api/budget/budget";
import { show, save, store } from "@/api/propertyPlan";
import { moneyFormatter, parseTime } from "@/utils";
import { getparameter } from "@/api/system/dictionary";
import {listdeptNoAuth} from "@/api/system/department";
export default {
  props: {
    departments: Array,
    role: {
      type: Number,
      default: 0,
    },
    lists: Array
  },
  data() {
    return {
      isShowModal: false,
      isShow: false,
      id: "",
      pid: "",
      type: "",

      itemTable: [
        {
          prop: "content",
          label: "评审内容",
          minWidth: 200,
          sortable: false,
          customFn: (row) => {
            return (
              <el-select
                filterable={true}
                allow-create={true}
                placeholder="评审内容"
                readonly={this.role == 1}
                style="width: 100%;"
                v-model={row.content}
                size="mini"
                clearable={true}
              >
                {
                  ['概算评审','预算评审','竣工结算评审','竣工财务评审'].map(i => {
                    return (
                      <el-option label={i} value={i}></el-option>
                    )
                  })
                }
              </el-select>
            );
          },
        },
        {
          prop: "plan_date",
          label: "计划评审时间",
          sortable: false,
          width: 160,
          customFn: (row) => {
            return (
              <el-date-picker
                type="month"
                placeholder="计划评审时间"
                readonly={this.role == 1}
                style="width: 100%;"
                value-format="yyyy-MM-dd"
                v-model={row.plan_date}
                size="mini"
                clearable={true}
              ></el-date-picker>
            );
          },
        },
        {
          prop: "actually_date",
          label: "实际评审时间",
          sortable: false,
          width: 160,
          customFn: (row) => {
            return (
              <el-date-picker
                placeholder="实际评审时间"
                readonly={this.role == 0}
                style="width: 100%;"
                value-format="yyyy-MM-dd"
                v-model={row.actually_date}
                size="mini"
                clearable={true}
              ></el-date-picker>
            );
          },
        },
        {
          prop: "date",
          label: "出具报告时间",
          sortable: false,
          width: 160,
          customFn: (row) => {
            return (
              <el-date-picker
                placeholder="出具报告时间"
                style="width: 100%;"
                value-format="yyyy-MM-dd"
                v-model={row.date}
                size="mini"
                clearable={true}
              ></el-date-picker>
            );
          },
        },
        {
          label: "操作",
          width: 180,
          align: "left",
          sortable: false,
          customFn: (row, scope) => {
            return (
              <Poptip
                confirm={true}
                transfer={true}
                placement="bottom"
                title="确认要删除吗"
                on={{
                  ["on-ok"]: (_) => {
                    this.form.item_list.splice(scope.$index, 1);
                  },
                }}
              >
                <Button
                  style="margin-left: 4px;"
                  ghost
                  size="small"
                  type="error"
                >
                  删除
                </Button>
              </Poptip>
            );
          },
        },
      ],
      detail: {},
      rowName: "",
      tempRow: {},
      form: {
        pid: '',
        project_name: "",
        state: 0,
        item_list: [],
        content_list: [],
        attachment_list: [],
        // content: "",
        // plan_date: "",
        // actually_date: "",
      },
      rules: {
        actually_date: [
          {
            validator: (rule, value, callback) => {
              if (this.role == 1) {
                value ? callback() : callback(new Error("请选择实际时间"));
              } else {
                callback();
              }
            },
            message: "请选择实际时间",
          },
        ],
        plan_date: [
          {
            validator: (rule, value, callback) => {
              if (this.role == 0) {
                value ? callback() : callback(new Error("请选择计划时间"));
              } else {
                callback();
              }
            },
            message: "请选择计划时间",
          },
        ],
      },

      moneyWay: [],
      budgets: [],
      budgetTotal: 0,
      budgetSelect: {
        keyword: '',
        department_id: '',
        year: '',
        page: 1,
        page_size: 20,
        purchase_type_id: 1,
        type:3,
      },
      budgetTable: [
        {
          title: "名称",
          width: 200,
          align: "left",
          key: "name",
          fixed: "left",
        },
        {
          title: "采购形式",
          width: 120,
          align: "center",
          render: (h, { row, column }) =>
            h("span", row?.purchase_type?.value || "无"),
        },
        {
          title: "项目类型",
          width: 120,
          key: "type",
          align: "center",
          render: (h, { row }) => {
            let map = new Map([
              [1, "服务"],
              [2, "货物"],
              [3, "工程"],
            ]);
            return h("span", map.get(row.type) || "无");
          },
        },
        {
          title: "采购方式",
          width: 120,
          align: "center",
          render: (h, { row, column }) =>
            h("span", row?.purchase_way?.value || "无"),
        },
        {
          title: "资金来源",
          width: 120,
          align: "center",
          render: (h, { row }) =>
            h("div", [
              row.money_way_detail.map((item) => h("span", item.value)),
            ]),
        },
        {
          title: "已申请金额(元)",
          key: "apply_money_total",
          width: 140,
          align: "right",
          render: (h, { row }) =>
            h(
              "span",
              Number(row.apply_money_total || 0)
                .toFixed(2)
                .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
            ),
        },
        {
          title: "已付金额(元)",
          key: "fund_log_total",
          width: 140,
          align: "right",
          render: (h, { row }) =>
            h(
              "span",
              Number(row.fund_log_total || 0)
                .toFixed(2)
                .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
            ),
        },
        {
          title: "合同预算价(元)",
          key: "plan_price",
          width: 140,
          align: "right",
          render: (h, { row }) =>
            h(
              "span",
              Number(row.plan_price || 0)
                .toFixed(2)
                .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
            ),
        },
        {
          title: "合同签订价(元)",
          key: "money",
          width: 140,
          align: "right",
          render: (h, { row }) =>
            h(
              "span",
              Number(row.money || 0)
                .toFixed(2)
                .replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
            ),
        },
      ],
    };
  },
  methods: {
    showModal () {
      this.isShowModal = true
    },
    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.pid });
      console.log(res.item.find((i) => i.id === this.id));
      this.$integrateData(this.form, res);
      console.log(this.form)
      this.rowName = res.project?.name;
      this.form.item_list = res.item?.map((i) => {
        return {
          content: i.content || '',
          plan_date: i.plan_date || '',
          actually_date: i.actually_date || '',
          date: i.date || ''
        };
      });
    },

    submit() {
      if (this.type === "add") {
        store(this.form).then((res) => {
          this.$message({
            type: "success",
            message: "新增成功",
          });
          this.hidden();
          this.$emit("refresh");
        });
      }
      if (this.type === "editor") {
        save({
          id: this.pid,
          ...this.form,
        }).then((res) => {
          this.$message({
            type: "success",
            message: "编辑成功",
          });
          this.hidden();
          this.$emit("refresh");
        });
      }
      // let temp = this.detail.item?.find((i) => i.id === this.id);
      // let index = this.detail.item?.indexOf(temp);
      // this.detail.item?.splice(index, 1, this.form);
      // this.detail.item_list = this.detail.item.map((i) => {
      //   return {
      //     content: i.content,
      //     actually_date: i.actually_date,
      //     plan_date: i.plan_date,
      //   };
      // });
      //
      // save(this.detail).then((res) => {
      //   this.$message({
      //     type: "success",
      //     message: "保存成功",
      //   });
      //   this.hidden();
      //   this.$emit("refresh");
      // });
    },

    async getContract() {
      const res = await getContract(this.budgetSelect);
      this.budgets = res.list.data;
      this.budgetTotal = res.list.total;
    },

    async getMoneyWay() {
      const res = await getparameter({
        number: "money_way",
      });
      this.moneyWay = res.detail;
    },

    rowPick(row) {
      if (this.isShow) {
        this.form.project_name = row.name;
      } else {
        this.$emit('rowPick', row)
      }
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        if (this.type === "editor") {
          this.getDetail();
        }
      } else {
        this.id = "";
        this.type = "";
        this.rowName = "";
        this.init();
        this.$refs["dialog"].clearValidate();
        delete this.form.id;
      }
    },
  },
  created() {
    this.getMoneyWay();
    this.getContract();
  },
};
</script>

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

.select {

  margin-bottom: 10px;

  & > * {
    margin-left: 6px;
  }
}
::v-deep .el-input__suffix {
  right: 0;
}
</style>
